天天看点

linux检查进程是否正在正常运行

1、popen函数

 popen() 函数 用 创建管道 的 方式启动一个 进程, 并调用 shell. 因为 管道是被定义成单向的, 所以 type 参数 只能定义成 只读或者 只写, 不能是 两者同时, 结果流也相应的 是只读 或者 只写.

command 参数 是 一个 字符串指针, 指向的是一个 以 null 结束符 结尾的字符串, 这个字符串包含 一个 shell 命令. 这个命令 被送到 /bin/sh 以 -c 参数 执行, 即由 shell 来执行. type 参数 也是 一个 指向 以 null 结束符结尾的 字符串的指针, 这个字符串 必须是 'r' 或者 'w’ 来指明 是 读还是写.

2、strsep函数

原型:char *strsep(char **stringp, const char *delim); 功能:分解字符串为一组字符串。从stringp指向的位置起向后扫描,遇到delim指向的字符串中的字符后,将此字符替换为NULL,返回stringp指向的地址。它适用于分割“关键字”在两个字符串之间只“严格出现一次”的情况。

3、程序思路

是先用shell找出进程名,然后发信号0确认进程是否在正常运行, 代码如下:

static int check_pid(const char *psAppName)

{

FILE *psFile = NULL; 

int iRet = FAIL;

char acCmd[128] = {0};

char acBuff[PID_INFO] = {0};

char *p = acBuff;

pid_t iWnePid = -1;

char *psStrtok = NULL;

memset(acCmd,0,sizeof(acCmd));

memset(acBuff,0,sizeof(acBuff));

snprintf(acCmd, sizeof(acCmd),"ps -ef|grep %s",psAppName);

debuging("acCmd = %s\n", acCmd);

psFile = popen(acCmd, "r");

if(NULL == psFile)

{

debuging("psFile == NULL\n");

return FAIL; 

}

if (NULL == fgets(acBuff, PID_INFO, psFile))

{

return FAIL;

}

debuging("acBuff = %s\n", acBuff);

if (strlen(acBuff) > 0)

{

while((psStrtok = strsep(&p, " ")))

{

//debuging("psStrtok = %s\n", psStrtok);

if(NULL == psStrtok)

if(0 == strlen(psStrtok))

return FAIL; 

}

else

{

debuging("psStrtok = %s\n", psStrtok);

if (strlen(psStrtok) > 0)

{

if(0 == (iWnePid = atoi(psStrtok)))

{

printf("GetPid Failed\n");

return FAIL; 

}

else

{

printf("iWnePid = %d\n", iWnePid);

break;

}

}

}

}

}

pclose(psFile); 

iRet = kill(iWnePid, 0);

debuging("iRet = %d\n", iRet);

if(0 == iRet)

{

iRet = WNET_EXIST;

printf("process: %s exist!\n",psAppName);

}

else 

{

memset(acCmd,0,sizeof(acCmd));

snprintf(acCmd, sizeof(acCmd), "kill -9 %d", iWnePid);

debuging("process: %s not exist!, acCmd = %s\n",psAppName, acCmd);

}

return iRet;

}