Linux - get process pid

How can I get the PID of a service called abc using C ++ on Linux without using a system call? I would appreciate any examples you want to offer.

+4
source share
2 answers

Google covers it :)

http://programming-in-linux.blogspot.com/2008/03/get-process-id-by-name-in-c.html

Although it uses sysctl, which is a system call!

This is C, but should work just as well in C ++

+3
source

Since using sysctl not been recommended for centuries, the recommended way to do this is to examine each of the process entries in /proc and read the comm file in each folder. If for your example the contents of this file are abc\n , then the process you are looking for.

I really don't speak C ++, but here is a possible solution in POSIX C89:

 #include <glob.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> pid_t find_pid(const char *process_name) { pid_t pid = -1; glob_t pglob; char *procname, *readbuf; int buflen = strlen(process_name) + 2; unsigned i; /* Get a list of all comm files. man 5 proc */ if (glob("/proc/*/comm", 0, NULL, &pglob) != 0) return pid; /* The comm files include trailing newlines, so... */ procname = malloc(buflen); strcpy(procname, process_name); procname[buflen - 2] = '\n'; procname[buflen - 1] = 0; /* readbuff will hold the contents of the comm files. */ readbuf = malloc(buflen); for (i = 0; i < pglob.gl_pathc; ++i) { FILE *comm; char *ret; /* Read the contents of the file. */ if ((comm = fopen(pglob.gl_pathv[i], "r")) == NULL) continue; ret = fgets(readbuf, buflen, comm); fclose(comm); if (ret == NULL) continue; /* If comm matches our process name, extract the process ID from the path, convert it to a pid_t, and return it. */ if (strcmp(readbuf, procname) == 0) { pid = (pid_t)atoi(pglob.gl_pathv[i] + strlen("/proc/")); break; } } /* Clean up. */ free(procname); free(readbuf); globfree(&pglob); return pid; } 

Caution: if there are several running processes with the name you are looking for, this code will only return one. If you are going to change this, keep in mind that with a naive globe, you will also consider /proc/self/comm , which could potentially lead to duplicate entries.

If there are multiple processes with the same name, there really is no way to guarantee that you got the right one. For this reason, many daemons have the ability to save their files to a file; check your documentation.

+3
source

Source: https://habr.com/ru/post/1342809/


All Articles