Admin/bash_process/bash_process.c
author wenzelm
Sat Feb 13 22:52:41 2016 +0100 (2016-02-13)
changeset 62300 f41884b9c4f1
parent 62293 72f6d6fd5853
child 62567 cb4e6ca06505
permissions -rw-r--r--
actually wait for forked process and return its status -- this is not meant to be a daemon;
     1 /*  Author:     Makarius
     2 
     3 Bash process with separate process group id.
     4 */
     5 
     6 #include <stdlib.h>
     7 #include <stdio.h>
     8 #include <string.h>
     9 #include <sys/types.h>
    10 #include <sys/wait.h>
    11 #include <unistd.h>
    12 
    13 static void fail(const char *msg)
    14 {
    15   fprintf(stderr, "%s\n", msg);
    16   fflush(stderr);
    17   exit(2);
    18 }
    19 
    20 
    21 int main(int argc, char *argv[])
    22 {
    23   /* args */
    24 
    25   if (argc < 2) {
    26     fprintf(stderr, "Bad arguments: missing pid file\n");
    27     fflush(stderr);
    28     exit(1);
    29   }
    30   char *pid_name = argv[1];
    31 
    32 
    33   /* setsid */
    34 
    35   if (setsid() == -1) {
    36     pid_t pid = fork();
    37     int status;
    38 
    39     if (pid == -1) fail("Cannot set session id (failed to fork)");
    40     else if (pid != 0) {
    41       if (waitpid(pid, &status, 0) == -1) {
    42         fail("Cannot join forked process");
    43       }
    44 
    45       if (WIFEXITED(status)) {
    46         exit(WEXITSTATUS(status));
    47       }
    48       else if (WIFSIGNALED(status)) {
    49         exit(128 + WTERMSIG(status));
    50       }
    51       else {
    52         fail("Unknown status of forked process");
    53       }
    54     }
    55     else if (setsid() == -1) fail("Cannot set session id (after fork)");
    56   }
    57 
    58 
    59   /* report pid */
    60 
    61   if (strcmp(pid_name, "-") == 0) {
    62     fprintf(stdout, "%d\n", getpid());
    63     fflush(stdout);
    64   }
    65   else if (strlen(pid_name) > 0) {
    66     FILE *pid_file;
    67     pid_file = fopen(pid_name, "w");
    68     if (pid_file == NULL) fail("Cannot open pid file");
    69     fprintf(pid_file, "%d", getpid());
    70     fclose(pid_file);
    71   }
    72 
    73 
    74   /* shift command line */
    75 
    76   int i;
    77   for (i = 2; i < argc; i++) {
    78     argv[i - 2] = argv[i];
    79   }
    80   argv[argc - 2] = NULL;
    81   argv[argc - 1] = NULL;
    82 
    83 
    84   /* exec */
    85 
    86   execvp("bash", argv);
    87   fail("Cannot exec process");
    88 }