获取运行firefox进程的PID

时间:2016-04-26 20:46:03

标签: c linux operating-system

如何在C中获得“firefox”进程的PID?

在此代码中,system仅返回0,表示成功。我怎样才能获得PID?

int x = system("pidof -s firefox");
printf("%d\n", x);

1 个答案:

答案 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