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

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


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.


Use sysctl - Example code

EDIT - it is available in Linux see here


Procfs reads are very cheap, many people think of iterating through /proc like they would iterating through / , its really not the case at all.

Save some time by skipping any entry that is under 1000, there's no sense in examining kernel threads. So, basically .. after opendir(), if strtoint() thinks the entry is an int , and that int is greater than or equal to 1000, just read /proc/%d/stat.

Try to avoid the urge to just resolve the 'exe' link, as that is not going to tell you the state of the process that will be receiving the signal. For instance, if the target is in state 'D' (disk sleep), you'd want to know as the signal will not be immediately delivered, or perhaps never, if the D state is perennial.

On most systems, there's going to be 70 - 120 processes to examine and you'll often find your target way before reaching the end.