當需要kil一個進程時,需要提供一個pid(使用kill命令)或提供一個進程名(使用pkill命令)。
pkill是如何通過進程名得到進程id的?
在linux中進程是通過文件來表示的,信息都存儲在/proc/pid目錄中。
在/proc/pid/status文件的第一行,保存有進程名,和用戶輸入的進行比對,如果一致,就添加到動態數組中,最后返回。
附代碼:
long* find_pid_by_name( char* pidName)
{
DIR *dir;
struct dirent *next;
long* pidList=NULL;
int i=0;
///proc中包括當前的進程信息,讀取該目錄
dir = opendir("/proc");
if (!dir)
perror_msg_and_die("Cannot open /proc");
//遍歷
while ((next = readdir(dir)) != NULL) {
FILE *status;
char filename[READ_BUF_SIZE];
char buffer[READ_BUF_SIZE];
char name[READ_BUF_SIZE];
/* Must skip ".." since that is outside /proc */
if (strcmp(next->d_name, "..") == 0)
continue;
/* If it isn't a number, we don't want it */
if (!isdigit(*next->d_name))
continue;
//設置進程
sprintf(filename, "/proc/%s/status", next->d_name);
if (! (status = fopen(filename, "r")) ) {
continue;
}
if (fgets(buffer, READ_BUF_SIZE-1, status) == NULL) {
fclose(status);
continue;
}
fclose(status);
//得到進程id
/* Buffer should contain a string like "Name: binary_name" */
sscanf(buffer, "%*s %s", name);
if (strcmp(name, pidName) == 0) {
pidList=realloc( pidList, sizeof(long) * (i+2));
pidList[i++]=strtol(next->d_name, NULL, 0);
}
}
if (pidList) {
pidList[i]=0;
}
return NULL;
}
注:該代碼在busybox0.6.3/libbb/find_pid_by_name.c
