當需要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