应该工作一样,现在,这样的推荐方法是通过检查每个过程中的条目在/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保存到文件中;检查你的文件。