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