- 论坛徽章:
- 0
|
有没有系统调用可以判断某进程是否存在?
下面的代码 执行时出现如下问题:当进程不存在时is_proc_exist里的line为1,好象是grep -v "grep"不起作用,请问是什么原因?
#include <stdio.h>; /* FILE, sprintf, fgets, puts */
#include <stdlib.h>; /* atoi, exit, EXIT_SUCCESS */
#include <string.h>; /* strtok, strcmp */
#include <sys/types.h>; /* pid_t */
#include <sys/wait.h>; /* WIFEXITED, WEXITSTATUS */
bool is_proc_exist(char *filter)
{
static char line[133], command[80], *linep, *token, *cmd;
FILE *fp;
int status;
if (filter == NULL) return false;
sprintf(command, "ps -ef |grep -v grep | grep %s | wc -l", filter); //ps -ef | grep "process" | grep -v "g
rep"
printf("%s\n", command);
fp = popen(command, "r" ;
if ((FILE *)0 == fp) return false;
if ((char *)0 == fgets(line, sizeof line, fp))
{
pclose(fp);
return false;
}
printf("%s\n", line);
if (atoi(line) >; 0)
{
return true;
}
else
{
return false;
}
}
int main(int argc, char *argv[])
{
if (is_proc_exist(argv[1]))
printf("%s already run\n", argv[1]);
else
printf("%s not run\n", argv[1]);
return 0;
} |
|