开发者

C program under Linux: how to find out if another program is running

My C program running under Linux wants to find out, by name, if ano开发者_JS百科ther program is running. How to do it?


There are two ways basically:

  • Use popen("pgrep yourproc", "r"); and then fgets from it
  • Use opendir and readdir to parse /proc - this is basically what ps(1) does

Not the cleanest but I would go with the first of these.


Travesing /proc really isn't much harder than popen(). Essentially you do 3 things

  • Open all number formatted /proc entries.
  • Get the command invocation through /proc/<PID>/command/
  • Perform a regex match for the name of the processs you want.

I've omitted some error handling for clarity, but It should do something like what you want.

int 
main()
{
    regex_t number;
    regex_t name;
    regcomp(&number, "^[0-9]+$", 0);
    regcomp(&name, "<process name>", 0);
    chdir("/proc");
    DIR* proc = opendir("/proc");
    struct dirent *dp;
    while(dp = readdir(proc)){
         if(regexec(&number, dp->d_name, 0, 0, 0)==0){
              chdir(dp->d_name);
              char buf[4096];
              int fd = open("cmdline", O_RDONLY);
              buf[read(fd, buf, (sizeof buf)-1)] = '\0';
              if(regexec(&name, buf, 0, 0, 0)==0)
                    printf("process found: %s\n", buf);
              close(fd);
              chdir("..");
         }
    }
    closedir(proc);
    return 0;
}


In unix, programs do not run. Processes run. A process can be viewed as an instance of a program. A process can operate under another name or change its name, or have no name at all. Also, at the time of running, the program can even have ceased to exits (on disk) and only exist in core. Take for instance the following program: (is /dev/null actually running? I don't think so ...)

#include <unistd.h>
#include <string.h>

int main(int arc, char **argv)
{

if (strcmp(argv[0], "/dev/null") ) {
    execl( argv[0], "/dev/null", NULL );
    }

sleep (30);
return 0;
}


If you want to look at the 'right' way to do this, check out the following:

Linux API to list running processes?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜