prototype vfork exec-wrapper.
[ardour.git] / tools / exec_wrapper.c
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <fcntl.h>
6
7 #ifndef STDIN_FILENO
8 #define STDIN_FILENO 0
9 #endif
10 #ifndef STDOUT_FILENO
11 #define STDOUT_FILENO 1
12 #endif
13 #ifndef STDERR_FILENO
14 #define STDERR_FILENO 2
15 #endif
16
17 extern char **environ;
18 static void close_fd (int *fd) { if ((*fd) >= 0) close (*fd); *fd = -1; }
19
20 int main(int argc, char *argv[]) {
21         if (argc < 10) {
22                 // TODO: if argv > 3, assume pok[] is given, notifify parent.
23                 // usage() and a man-page (help2man) would not be bad, either :)
24                 return -1;
25         }
26
27         int pok[2];
28         int pin[2];
29         int pout[2];
30
31         pok[0]  = atoi(argv[1]);
32         pok[1]  = atoi(argv[2]);
33         pin[0]  = atoi(argv[3]);
34         pin[1]  = atoi(argv[4]);
35         pout[0] = atoi(argv[5]);
36         pout[1] = atoi(argv[6]);
37
38         int stderr_mode = atoi(argv[7]);
39         int nicelevel = atoi(argv[8]);
40
41         /* vfork()ed child process - exec external process */
42         close_fd(&pok[0]);
43         fcntl(pok[1], F_SETFD, FD_CLOEXEC);
44
45         close_fd(&pin[1]);
46         if (pin[0] != STDIN_FILENO) {
47                 dup2(pin[0], STDIN_FILENO);
48         }
49         close_fd(&pin[0]);
50         close_fd(&pout[0]);
51         if (pout[1] != STDOUT_FILENO) {
52                 dup2(pout[1], STDOUT_FILENO);
53         }
54
55         if (stderr_mode == 2) {
56                 /* merge STDERR into output */
57                 if (pout[1] != STDERR_FILENO) {
58                         dup2(pout[1], STDERR_FILENO);
59                 }
60         } else if (stderr_mode == 1) {
61                 /* ignore STDERR */
62                 close(STDERR_FILENO);
63         } else {
64                 /* keep STDERR */
65         }
66
67         if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
68                 close_fd(&pout[1]);
69         }
70
71         if (nicelevel !=0) {
72                 nice(nicelevel);
73         }
74
75         /* copy current environment */
76         char **envp = NULL;
77         int i=0;
78         envp = (char **) calloc(1, sizeof(char*));
79         for (i=0;environ[i];++i) {
80                 envp[i] = strdup(environ[i]);
81                 envp = (char **) realloc(envp, (i+2) * sizeof(char*));
82         }
83         envp[i] = 0;
84
85         /* all systems go */
86         execve(argv[9], &argv[9], envp);
87
88         /* if we reach here something went wrong.. */
89         char buf = 0;
90         (void) write(pok[1], &buf, 1 );
91         close_fd(&pok[1]);
92         exit(-1);
93         return -1;
94 }