Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a program ended its execution via a signal?

Tags:

c

linux

signals

I'm writing a program monitor as an assignment for an operating systems course (very basic though, like an introduction to it).

One of the things the monitor has to do is to show the termination code of the program it was monitoring if it ended by "natural causes" or the code of the signal responsible for its termination.

Right now I'm just waiting for the child to end its execution and then capturing its termination code. This is the related code snippet:

pid_t id = -1;
switch (id = fork()) {
    // Error when forking:
    case -1:
        error(-1, "Something went wrong when forking.");
        exit(-1);
    // Code for the child process:
    case 0:
        // Just launch the program we're asked to:
        execvp(argv[2], &argv[2]);
        // If reached here it wasn't possible to launch the process:
        error(1, "Process could not be launched.");
        exit(1);
    // Code for the parent process:
    default:
        // Just wait for the child to finish its execution:
        wait(&return_value);
}

error(2) is a logger function, just to simplify the code whenever an error arises.

Depending on how the process I have to show different statements:

Process ended: X

or

Process terminated with signal X.

Where X would be the termination code or the signal received. How could we know if the child process ended because of a signal?

like image 542
Johannes Avatar asked Dec 22 '10 08:12

Johannes


1 Answers

From wait(2):

   WIFSIGNALED(status)
          returns true if the child process was terminated by a signal.
   WTERMSIG(status)
          returns  the  number  of the signal that caused the child process to terminate.

So you need to check WIFSIGNALED(return_value) and if it is true, check WTERMSIG(return_value).

like image 70
wRAR Avatar answered Oct 28 '22 07:10

wRAR