Question

I want my program to output how the process has exited, as seen in the second line after the user's prompt and input.

shell> wait
shell: process has exited abnormally with signal 11: Segmentation fault.

What function would I use in my printf()? I thought of exit() but that returns void. Could it be strsignal, if so, what would I pass as the int for strsignal? Thank you!

No correct solution

OTHER TIPS

You are correct, it is strsignal(). See this example: https://www.cs.fsu.edu/~baker/opsys/examples/forkexec/print_child_status.c

Relevant portion:

#include <stdio.h>
#include <wait.h>
#include <string.h>

void print_child_status (int status) {
  if (WIFEXITED (status)) {
    fprintf (stdout, "Child exited with status %d\n", WEXITSTATUS (status));
  } else if (WIFSTOPPED (status)) {
    fprintf (stdout, "Child stopped by signal %d (%s)\n", WSTOPSIG (status), strsignal (WSTOPSIG (status)));
  } else if (WIFSIGNALED (status)) {
    fprintf (stdout, "Child killed by signal %d (%s)\n", WTERMSIG (status), strsignal (WTERMSIG (status)));
  } else {
    fprintf (stdout, "Unknown child status\n");
  }
}

You can refer to the code at towards the end in the following link http://linux.die.net/man/2/waitpid

The demonstration of the program:

$ ./a.out &
Child PID is 32360
[1] 32359
$ kill -STOP 32360
stopped by signal 19
$ kill -CONT 32360
continued
$ kill -TERM 32360
killed by signal 15
[1]+  Done                    ./a.out
$

Source of the program:

#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

int
main(int argc, char *argv[])
{
    pid_t cpid, w;
    int status;

   cpid = fork();
    if (cpid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

   if (cpid == 0) {            /* Code executed by child */
        printf("Child PID is %ld\n", (long) getpid());
        if (argc == 1)
            pause();                    /* Wait for signals */
        _exit(atoi(argv[1]));

   } else {                    /* Code executed by parent */
        do {
            w = waitpid(cpid, &status, WUNTRACED | WCONTINUED);
            if (w == -1) {
                perror("waitpid");
                exit(EXIT_FAILURE);
            }

           if (WIFEXITED(status)) {
                printf("exited, status=%d\n", WEXITSTATUS(status));
            } else if (WIFSIGNALED(status)) {
                printf("killed by signal %d\n", WTERMSIG(status));
            } else if (WIFSTOPPED(status)) {
                printf("stopped by signal %d\n", WSTOPSIG(status));
            } else if (WIFCONTINUED(status)) {
                printf("continued\n");
            }
        } while (!WIFEXITED(status) && !WIFSIGNALED(status));
        exit(EXIT_SUCCESS);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top