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