1 /* ISC license. */
2 
3 #include <unistd.h>
4 #include <errno.h>
5 #include <sys/wait.h>
6 
7 #include <skalibs/strerr2.h>
8 #include <skalibs/allreadwrite.h>
9 #include <skalibs/djbunix.h>
10 #include <skalibs/exec.h>
11 
12 #define USAGE "s6-fghack prog..."
13 
main(int argc,char const * const * argv)14 int main (int argc, char const *const *argv)
15 {
16   int p[2] ;
17   int pcoe[2] ;
18   pid_t pid ;
19   char dummy ;
20   PROG = "s6-fghack" ;
21   if (argc < 2) strerr_dieusage(100, USAGE) ;
22   if (pipe(p) < 0) strerr_diefu1sys(111, "create hackpipe") ;
23   if (pipe(pcoe) < 0) strerr_diefu1sys(111, "create coepipe") ;
24 
25   switch (pid = fork())
26   {
27     case -1 : strerr_diefu1sys(111, "fork") ;
28     case 0 :
29     {
30       int i = 0 ;
31       close(p[0]) ;
32       close(pcoe[0]) ;
33       if (coe(pcoe[1]) < 0) _exit(111) ;
34       for (; i < 30 ; i++) dup(p[1]) ; /* hack. gcc's warning is justified. */
35       exec(argv+1) ;
36       i = errno ;
37       if (fd_write(pcoe[1], "", 1) < 1) _exit(111) ;
38       _exit(i) ;
39     }
40   }
41 
42   close(p[1]) ;
43   close(pcoe[1]) ;
44 
45   switch (fd_read(pcoe[0], &dummy, 1))
46   {
47     case -1 : strerr_diefu1sys(111, "read on coepipe") ;
48     case 1 :
49     {
50       int wstat ;
51       if (wait_pid(pid, &wstat) < 0) strerr_diefu1sys(111, "wait_pid") ;
52       errno = WEXITSTATUS(wstat) ;
53       strerr_dieexec(111, argv[1]) ;
54     }
55   }
56 
57   fd_close(pcoe[0]) ;
58 
59   p[1] = fd_read(p[0], &dummy, 1) ;
60   if (p[1] < 0) strerr_diefu1sys(111, "read on hackpipe") ;
61   if (p[1]) strerr_dief2x(102, argv[1], " wrote on hackpipe") ;
62 
63   {
64     int wstat ;
65     if (wait_pid(pid, &wstat) < 0) strerr_diefu1sys(111, "wait_pid") ;
66     if (WIFSIGNALED(wstat)) strerr_dief2x(111, argv[2], " crashed") ;
67     return WEXITSTATUS(wstat) ;
68   }
69 }
70