How to find if a process is running in C?

I would like to know if the process is working. I do NOT want to use any system ("") commands. Is there a C-based feature that lets you know if a process is running?

I would like to indicate the name of the process and find out if it works.

Thanks,

+9
source share
4 answers

Of course, 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 in progress; this can be used to check for a process id or process group id.

So just call kill(pid, 0) for the ID of the process you want to check and see if there is an error ( ESRCH ).

+11
source

On Linux, another way to do this may include checking the contents of the /proc directory. Numbered directories are process identifiers, and subdirectories containing the cmdline file show the name of the command.

For example, if /proc/1234/cmdline contains the value foo , then the process foo has the identifier 1234. Thus, names can be mapped to PIDs using the standard file access functions in C. See proc(5) for more information.

+2
source

You may find this interesting: http://programming-in-linux.blogspot.com/2008/03/get-process-id-by-name-in-c.html

The β€œusual and best way” is to read the /proc folder. You can see this question , which refers to http://procps.sourceforge.net/ , which may interest you

+1
source

You can scan the /proc file system for all currently running processes and see if the cmdline entry matches what you want for this particular process.

However, there is a race condition. The process may die after you decide that it works.

The surefire way to find out if your process is running is the one that started the process. Then, when the child dies, you will receive SIGCHLD , and you can use waitpid(-1,..) to find out which child has died.

0
source

All Articles