如何在C中获得“firefox”进程的PID?
在此代码中,system
仅返回0,表示成功。我怎样才能获得PID?
int x = system("pidof -s firefox");
printf("%d\n", x);
答案 0 :(得分:1)
popen
是你想要的:它打开一个进程,打开进程的输出可以读取就像用fopen
打开的文件流一样:
FILE *f = popen("pgrep firefox", "r");
if (NULL == f)
{
perror("popen");
}
else
{
char buffer[128];
while (fgets(buffer, sizeof buffer, f))
{
// do something with read line
int pid;
sscanf(buffer, "%d", &pid)
}
// close the process
pclose(f);
}
请参阅man popen