linux获取等待的进程pid,linux - 获取进程的pid

应该工作一样,现在,这样的推荐方法是通过检查每个过程中的条目在/proc和读取comm文件在每个文件夹中。如果,例如,该文件的内容是abc\n,那就是您正在寻找的过程。

我真的不说C++,但这里的在POSIX C89一个可能的解决方案:

#include

#include

#include

#include

pid_t find_pid(const char *process_name)

{

pid_t pid = -1;

glob_t pglob;

char *procname, *readbuf;

int buflen = strlen(process_name) + 2;

unsigned i;

/* Get a list of all comm files. man 5 proc */

if (glob("/proc/*/comm", 0, NULL, &pglob) != 0)

return pid;

/* The comm files include trailing newlines, so... */

procname = malloc(buflen);

strcpy(procname, process_name);

procname[buflen - 2] = '\n';

procname[buflen - 1] = 0;

/* readbuff will hold the contents of the comm files. */

readbuf = malloc(buflen);

for (i = 0; i < pglob.gl_pathc; ++i) {

FILE *comm;

char *ret;

/* Read the contents of the file. */

if ((comm = fopen(pglob.gl_pathv[i], "r")) == NULL)

continue;

ret = fgets(readbuf, buflen, comm);

fclose(comm);

if (ret == NULL)

continue;

/*

If comm matches our process name, extract the process ID from the

path, convert it to a pid_t, and return it.

*/

if (strcmp(readbuf, procname) == 0) {

pid = (pid_t)atoi(pglob.gl_pathv[i] + strlen("/proc/"));

break;

}

}

/* Clean up. */

free(procname);

free(readbuf);

globfree(&pglob);

return pid;

}

警告:如果有与您正在寻找的名称的多个正在运行的进程,这个代码将只返回一个。如果你打算改变这种情况,请注意,如果你写的是天真的glob,你也会检查/proc/self/comm,这可能会导致重复的输入。

如果有多个进程具有相同的名称,那么确实没有办法确保您获得正确的名称。由于这个原因,许多守护进程有能力将它们的pid保存到文件中;检查你的文件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值