2016-04-26 51 views
0

如何获取C中“firefox”进程的PID?获取运行firefox进程的PID

在此代码中,system仅返回0,表示成功。我如何获得PID?

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

好,否,706989是关于Python的,而不是C. –

+3

使用['popen'](http://linux.die.net/man/3/popen)而不是'system'。 – kaylum

+0

我已经重新提出了您的问题,以便于阅读;但我只是一个像你这样的人,所以如果你不同意,你可以改回它。 – immibis

回答

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