Monday, February 20, 2012
Get process id by name in Linux using C++
Although it seems like a pretty common activity, locating a running process by name is a little harder in Linux than you'd expect. Various solutions are available on the web, ranging from code relying on sysctl calls to samples that use the results from running certain bash scripts. The following implementation takes advantage of the functionality offered by the /proc filesystem. It enumerates all numeric (pid) entries and accesses the cmdline file to retrieve the program that was used to start the process and matches it against the requested process name.
Function getProcIdByName shown below accepts the name of the requested process and returns the pid if the process is found or -1 otherwise.