简体   繁体   English

Linux下的C程序:如何确定是否有其他程序正在运行

[英]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 another program is running. 在Linux下运行的我的C程序希望通过名称找出另一个程序是否正在运行。 How to do it? 怎么做?

There are two ways basically: 基本上有两种方法:

  • Use popen("pgrep yourproc", "r"); 使用popen("pgrep yourproc", "r"); and then fgets from it 然后fgets从它
  • Use opendir and readdir to parse /proc - this is basically what ps(1) does 使用opendirreaddir来解析/proc - 这基本上就是ps(1)作用

Not the cleanest but I would go with the first of these. 不是最干净的,但我会选择其中的第一个。

Travesing /proc really isn't much harder than popen() . Traveing /proc确实不比popen()更难。 Essentially you do 3 things 基本上你做3件事

  • Open all number formatted /proc entries. 打开所有数字格式/proc条目。
  • Get the command invocation through /proc/<PID>/command / 通过/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. 在unix中, 程序不运行。 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 ...) 以下面的程序为例:( / dev / null实际运行吗?我不这么认为......)

#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? Linux API列出正在运行的进程?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM