I would like to find out if a process is running. I DO NOT want to use any system("") commands. Is there any C based function that lets you know if a process is running?
I would like to provide the process name and want to know if it's running.
Thanks,
/proc/<PID> should exists if the process PID is still running. Use stat() system call to check for file existence.
The easiest way to find out if process is running is run ps aux command and grep process name. If you got output along with process name/pid, your process is running.
You can list running processes using the ps command (ps means process status). The ps command displays your currently running processes in real-time. This will display the process for the current shell with four columns: PID returns the unique process ID.
Type the ps aux to see all running process in Linux. Alternatively, you can issue the top command or htop command to view running process in Linux.
Sure, use kill(2)
:
#include <sys/types.h>
#include <signal.h>
int kill(pid_t pid, int sig);
If sig is 0, then no signal is sent, but error checking is still performed; this can be used to check for the existence of a process ID or process group ID.
So just call kill(pid, 0)
on the process ID of the process that you want to check for and see if you get an error (ESRCH
).
On Linux, another way to do this might include examining the contents of the /proc
directory. Numbered directories are process IDs, while subdirectories containing the cmdline
file show the name of the command.
For example, if /proc/1234/cmdline
contains the value foo
, then process foo
has an ID of 1234. You could map names to PIDs this way, using standard file access functions in C. See proc(5)
for more information.
You may find this interesting: http://programming-in-linux.blogspot.com/2008/03/get-process-id-by-name-in-c.html
The "conventional and best way" to do this is read the /proc
folder. You can see this question for more, which references http://procps.sourceforge.net/, which may be of interest to you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With