在linux中通過進程名獲得進程id

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.