Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if a process is running in C?

Tags:

c

linux

process

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,

like image 929
Kitcha Avatar asked Aug 02 '12 21:08

Kitcha


People also ask

How do you check if a process is still running in C?

/proc/<PID> should exists if the process PID is still running. Use stat() system call to check for file existence.

How do I know if process ID is running?

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.

How can I see what processes are 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.

How do you check if a process is running in Linux from C program?

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.


3 Answers

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).

like image 122
Kerrek SB Avatar answered Oct 06 '22 00:10

Kerrek SB


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.

like image 27
Alex Reynolds Avatar answered Oct 06 '22 00:10

Alex Reynolds


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

like image 22
cegfault Avatar answered Oct 05 '22 23:10

cegfault