rkb
rkb

Reputation: 11231

How to check if a process is running or got segfaulted or terminated in linux from its pid in my main() in c++

I am invoking several processes in my main and I can get the pid of that processes. Now I want to wait until all this processes have been finished and then clear the shared memory block from my parent process. Also if any of the process not finished and segfaulted I want to kill that process. So how to check from the pid of processes in my parent process code that a process is finished without any error or it gave broke down becoz of runtime error or any other cause, so that I can kill that process.

Also what if I want to see the status of some other process which is not a child process but its pid is known.

Code is appreciated( I am not looking for script but code ).

Upvotes: 2

Views: 4452

Answers (4)

user50049
user50049

Reputation:

From your updates, it looks like you also want to check on other processes, which are not children of your current process.

You can look at /proc/{pid}/status to get an overview of what a process is currently doing, its either going to be:

  • Running
  • Stopped
  • Sleeping
  • Disk (D) sleep (i/o bound, uninterruptable)
  • Zombie

However, once a process dies (fully, unless zombied) so does its entry in /proc. There's no way to tell if it exited successfully, segfaulted, caught a signal that could not be handled, or failed to handle a signal that could be handled. Not unless its parent logs that information somewhere.

It sounds like your writing a watchdog for other processes that you did not start, rather than keeping track of child processes.

Upvotes: 2

Dummy00001
Dummy00001

Reputation: 17420

waitpid() from SIGCHLD handler to catch the moment when application terminates itself. Note that if you start multiple processes you have to loop on waitpid() with WNOHANG until it returns 0.

kill() with signal 0 to check whether the process is still running. IIRC zombies still qualify as processes thus you have to have proper SIGCHLD handler for that to work.

Upvotes: 0

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84151

Look into waitpid(2) with WNOHANG option. Check the "fate" of the process with macros in the manual page, especially WIFSIGNALED().

Also, segfaulted process is already dead (unless SIGSEGV is specifically handled by the process, which is usually not a good idea.)

Upvotes: 4

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

If a program segfaults, you won't need to kill it. It's dead already.

Use the wait and waitpid calls to wait for children to finish and check the status for some idea of how they exiting. See here for details on how to use these functions. Note especially the WIFSIGNALED and WTERMSIG macros.

Upvotes: 1

Related Questions