[英]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.