2014/08/12

find_pid_by_cmdline

要寫一個送 kill 到指定程式的 code,所以先要弄出這個根據 command line 找到 pid 的 function
#include <dirent.h>

static int find_pid_by_cmdline(const char *cmdline)
{
DIR *dir;
struct dirent *entry;
char *name, *p;
char status[32];
char buf[1024];
FILE *fp;
int pid, i;

dir = opendir("/proc");
if (!dir)
return 0;

while (entry = readdir(dir)) {
name = entry->d_name;
if (!(*name >= '0' && *name <= '9'))
continue;

pid = atoi(name);
sprintf(status, "/proc/%d/cmdline", pid);
if ((fp = fopen(status, "r")) == NULL)
continue;

name = fgets(buf, sizeof(buf), fp);
fclose(fp);
if (name == NULL)
continue;

for (i=0; i<1024; i++) {
if (buf[i] == 0) {
if (buf[i+1] == 0) {
i = 1024;
} else {
buf[i] = ' ';
}
}
}

if (!strcmp(buf, cmdline)) {
closedir(dir);
return pid;
}
}
closedir(dir);

return 0;
}

沒有留言: