Admin/Cygwin/exec_process.c
author wenzelm
Wed Apr 25 22:53:35 2012 +0200 (2012-04-25)
changeset 47764 d141f1193789
child 47796 c37411691ee7
permissions -rw-r--r--
more direct bash process group invocation on Cygwin, bypassing extra sh.exe and perl.exe which tend to crash;
wenzelm@47764
     1
/*  Author:     Makarius
wenzelm@47764
     2
wenzelm@47764
     3
Bash process group invocation on Cygwin.
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
#include <process.h>
wenzelm@47764
    11
wenzelm@47764
    12
wenzelm@47764
    13
static void fail(const char *msg)
wenzelm@47764
    14
{
wenzelm@47764
    15
  printf("%s\n", msg);
wenzelm@47764
    16
  exit(2);
wenzelm@47764
    17
}
wenzelm@47764
    18
wenzelm@47764
    19
wenzelm@47764
    20
int main(int argc, char *argv[])
wenzelm@47764
    21
{
wenzelm@47764
    22
  /* args */
wenzelm@47764
    23
wenzelm@47764
    24
  if (argc != 3) {
wenzelm@47764
    25
    printf("Bad arguments\n");
wenzelm@47764
    26
    exit(1);
wenzelm@47764
    27
  }
wenzelm@47764
    28
  char *pid_name = argv[1];
wenzelm@47764
    29
  char *script = argv[2];
wenzelm@47764
    30
wenzelm@47764
    31
wenzelm@47764
    32
  /* report pid */
wenzelm@47764
    33
wenzelm@47764
    34
  FILE *pid_file;
wenzelm@47764
    35
  pid_file = fopen(pid_name, "w");
wenzelm@47764
    36
  if (pid_file == NULL) fail("Cannot open pid file");
wenzelm@47764
    37
  fprintf(pid_file, "%d", getpid());
wenzelm@47764
    38
  fclose(pid_file);
wenzelm@47764
    39
wenzelm@47764
    40
wenzelm@47764
    41
  /* setsid */
wenzelm@47764
    42
wenzelm@47764
    43
  if (getgid() == getpid()) fail("Cannot set session id");
wenzelm@47764
    44
  setsid();
wenzelm@47764
    45
wenzelm@47764
    46
wenzelm@47764
    47
  /* exec */
wenzelm@47764
    48
wenzelm@47764
    49
  char *cmd_line[4];
wenzelm@47764
    50
  cmd_line[0] = "/bin/bash";
wenzelm@47764
    51
  cmd_line[1] = "-c";
wenzelm@47764
    52
  cmd_line[2] = script;
wenzelm@47764
    53
  cmd_line[3] = NULL;
wenzelm@47764
    54
wenzelm@47764
    55
  int pid = spawnv(_P_NOWAIT, "/bin/bash", cmd_line);
wenzelm@47764
    56
  if (pid == -1) fail("Bad process");
wenzelm@47764
    57
  waitpid(pid);
wenzelm@47764
    58
}
wenzelm@47764
    59