[英]linux - get pid of process
如何在不使用系统调用的情况下在 Linux 上使用 C++ 获取名为abc
的服务的 PID? 我将不胜感激您愿意提供的任何示例。
由于多年来一直不鼓励使用sysctl
,因此推荐的方法是检查/proc
中的每个进程条目并读取每个文件夹中的comm
文件。 对于您的示例,如果该文件的内容是abc\n
,那么这就是您要查找的过程。
我真的不会说 C++,但这是 POSIX C89 中的一个可能的解决方案:
#include <glob.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
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 保存到文件中。 检查您的文档。
谷歌已经涵盖了这个:)
http://programming-in-linux.blogspot.com/2008/03/get-process-id-by-name-in-c.html
虽然它确实使用了 sysctl,这是一个系统调用!
它是 C,但在 C++ 中应该也能正常工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.