actually wait for forked process and return its status -- this is not meant to be a daemon;
authorwenzelm
Sat Feb 13 22:52:41 2016 +0100 (2016-02-13)
changeset 62300f41884b9c4f1
parent 62299 9e95a4afb8c3
child 62301 028e5b1ef9f9
actually wait for forked process and return its status -- this is not meant to be a daemon;
Admin/bash_process/bash_process.c
     1.1 --- a/Admin/bash_process/bash_process.c	Sat Feb 13 21:22:02 2016 +0100
     1.2 +++ b/Admin/bash_process/bash_process.c	Sat Feb 13 22:52:41 2016 +0100
     1.3 @@ -7,9 +7,9 @@
     1.4  #include <stdio.h>
     1.5  #include <string.h>
     1.6  #include <sys/types.h>
     1.7 +#include <sys/wait.h>
     1.8  #include <unistd.h>
     1.9  
    1.10 -
    1.11  static void fail(const char *msg)
    1.12  {
    1.13    fprintf(stderr, "%s\n", msg);
    1.14 @@ -34,8 +34,24 @@
    1.15  
    1.16    if (setsid() == -1) {
    1.17      pid_t pid = fork();
    1.18 +    int status;
    1.19 +
    1.20      if (pid == -1) fail("Cannot set session id (failed to fork)");
    1.21 -    else if (pid != 0) exit(0);
    1.22 +    else if (pid != 0) {
    1.23 +      if (waitpid(pid, &status, 0) == -1) {
    1.24 +        fail("Cannot join forked process");
    1.25 +      }
    1.26 +
    1.27 +      if (WIFEXITED(status)) {
    1.28 +        exit(WEXITSTATUS(status));
    1.29 +      }
    1.30 +      else if (WIFSIGNALED(status)) {
    1.31 +        exit(128 + WTERMSIG(status));
    1.32 +      }
    1.33 +      else {
    1.34 +        fail("Unknown status of forked process");
    1.35 +      }
    1.36 +    }
    1.37      else if (setsid() == -1) fail("Cannot set session id (after fork)");
    1.38    }
    1.39