Obtain the process ID using the process name in Linux

Source: Internet
Author: User
Tags pkill

When you need a Kil process, you need to provide a PID (using the kill command) or a process name (using the pkill command ).
How does pkill get the process ID through the process name?
In Linux, processes are represented by files, and information is stored in the/proc/PID directory.
In the first line of the/proc/Pid/status file, the process name is saved and compared with the user input. If the process name is consistent, it is added to the dynamic array and the result is returned.

AppendixCode:

Long * find_pid_by_name (char * pidname) {dir * dir; struct dirent * Next; long * pidlist = NULL; int I = 0; // the current process information is included in Proc, read this directory dir = opendir ("/proc"); If (! DIR) perror_msg_and_die ("cannot open/proc"); // traverse 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; // sets the process 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); // obtain the process ID/* buffer shoshould 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 ;}

note: the code is in busybox0.6.3/libbb/find_pid_by_name.c

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.