获取PID,当有程序名称片段时

时间:2013-12-10 15:43:17

标签: c linux pid ps

我需要杀死运行主类blabla.class的java进程。出于这个原因,我可以使用函数kill(pid_t, SIGKILL),但我需要PID ID

我可以运行linux命令ps-ax | grep blabla来查找PID ID。使用C进行此操作的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

调整Marco https://stackoverflow.com/a/8166467/1967396给出的链接:

#define LEN 100
char line[LEN];
FILE *cmd = popen("ps -ax | grep blabla", "r");

fgets(line, LEN, cmd);
// now parse `line` for the information you want, using sscanf perhaps?
// I believe the pid is the first word on the line returned, and it fits in an int:
int pid;
sscanf(line, "%d", &pid);

pclose(cmd);