Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find PID of a Process by Name without Using popen() or system()

I've a process name and I've to send a kill() signal to that process but I need its PID to call kill(). I would only like to use:

popen("pidof process_name");

as the last thing. Is there any other way to find out the process' PID? One way I could think of is to send a socket request to that process and ask to its PID.

The other way is a little too complicated for a simple code I'm writing: to do what pidof command's source code is actually doing (it uses a function call find_pid_by_name() but that's doing a lot of things).

If no simple solution is possible, I've to do this:

system("pkill <process_name>");

and check its return code. But will pkill be available for sure on all Linux machines?

like image 232
Srikanth Avatar asked Dec 17 '08 15:12

Srikanth


2 Answers

You mentioned you were using linux. It isn't the cleanest solution, but you can go through every entry in /proc and check the process name in cmdline against what you are looking for.

like image 143
Greg Rogers Avatar answered Oct 08 '22 11:10

Greg Rogers


Use sysctl - Example code

EDIT - it is available in Linux see here

like image 22
Martin Beckett Avatar answered Oct 08 '22 12:10

Martin Beckett