Admin/exec_process/exec_process.c
author wenzelm
Mon Sep 16 12:51:33 2013 +0200 (2013-09-16)
changeset 53658 9e8714b4661a
parent 50292 45fe12c9788e
child 62292 486236dcd4d7
permissions -rw-r--r--
updated to smlnj 110.76;
     1 /*  Author:     Makarius
     2 
     3 Bash process group invocation.
     4 */
     5 
     6 #include <stdlib.h>
     7 #include <stdio.h>
     8 #include <sys/types.h>
     9 #include <unistd.h>
    10 
    11 
    12 static void fail(const char *msg)
    13 {
    14   fprintf(stderr, "%s\n", msg);
    15   exit(2);
    16 }
    17 
    18 
    19 int main(int argc, char *argv[])
    20 {
    21   /* args */
    22 
    23   if (argc != 3) {
    24     fprintf(stderr, "Bad arguments\n");
    25     exit(1);
    26   }
    27   char *pid_name = argv[1];
    28   char *script = argv[2];
    29 
    30 
    31   /* setsid */
    32 
    33   if (setsid() == -1) {
    34     pid_t pid = fork();
    35     if (pid == -1) fail("Cannot set session id (failed to fork)");
    36     else if (pid != 0) exit(0);
    37     else if (setsid() == -1) fail("Cannot set session id (after fork)");
    38   }
    39 
    40 
    41   /* report pid */
    42 
    43   FILE *pid_file;
    44   pid_file = fopen(pid_name, "w");
    45   if (pid_file == NULL) fail("Cannot open pid file");
    46   fprintf(pid_file, "%d", getpid());
    47   fclose(pid_file);
    48 
    49 
    50   /* exec */
    51 
    52   char *cmd_line[4];
    53   cmd_line[0] = "bash";
    54   cmd_line[1] = "-c";
    55   cmd_line[2] = script;
    56   cmd_line[3] = NULL;
    57 
    58   execvp(cmd_line[0], cmd_line);
    59   fail("Cannot exec process");
    60 }
    61