1 /* ISC license. */
2 
3 #include <skalibs/sysdeps.h>
4 #include <errno.h>
5 
6 #ifdef SKALIBS_HASPOSIXSPAWN
7 
8 #include <signal.h>
9 #include <spawn.h>
10 #include <stdlib.h>
11 
12 #include <skalibs/config.h>
13 
child_spawn0(char const * prog,char const * const * argv,char const * const * envp)14 pid_t child_spawn0 (char const *prog, char const *const *argv, char const *const *envp)
15 {
16   pid_t pid ;
17   posix_spawnattr_t attr ;
18   int e ;
19   int nopath = !getenv("PATH") ;
20   e = posix_spawnattr_init(&attr) ;
21   if (e) goto err ;
22   {
23     sigset_t set ;
24     sigemptyset(&set) ;
25     e = posix_spawnattr_setsigmask(&attr, &set) ;
26     if (e) goto errattr ;
27     e = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGMASK) ;
28     if (e) goto errattr ;
29   }
30   if (nopath && (setenv("PATH", SKALIBS_DEFAULTPATH, 0) < 0)) { e = errno ; goto errattr ; }
31   e = posix_spawnp(&pid, prog, 0, &attr, (char *const *)argv, (char *const *)envp) ;
32   if (nopath) unsetenv("PATH") ;
33   posix_spawnattr_destroy(&attr) ;
34   if (e) goto err ;
35   return pid ;
36 
37  errattr:
38   posix_spawnattr_destroy(&attr) ;
39  err:
40   errno = e ;
41   return 0 ;
42 }
43 
44 #else
45 
46 #include <unistd.h>
47 #include <string.h>
48 
49 #include <skalibs/allreadwrite.h>
50 #include <skalibs/strerr2.h>
51 #include <skalibs/sig.h>
52 #include <skalibs/djbunix.h>
53 #include <skalibs/exec.h>
54 
child_spawn0(char const * prog,char const * const * argv,char const * const * envp)55 pid_t child_spawn0 (char const *prog, char const *const *argv, char const *const *envp)
56 {
57   pid_t pid ;
58   int e ;
59   int p[2] ;
60   if (pipecoe(p) < 0) return 0 ;
61   pid = fork() ;
62   if (pid < 0)
63   {
64     fd_close(p[1]) ;
65     fd_close(p[0]) ;
66     return 0 ;
67   }
68   if (!pid)
69   {
70     size_t len = strlen(PROG) ;
71     char name[len + 9] ;
72     memcpy(name, PROG, len) ;
73     memcpy(name + len, " (child)", 9) ;
74     PROG = name ;
75     fd_close(p[0]) ;
76     sig_blocknone() ;
77     exec_ae(prog, argv, envp) ;
78     e = errno ;
79     fd_write(p[1], (char *)&e, sizeof(e)) ;
80     _exit(127) ;
81   }
82   fd_close(p[1]) ;
83   p[1] = fd_read(p[0], (char *)&e, sizeof(e)) ;
84   if (p[1] < 0)
85   {
86     fd_close(p[0]) ;
87     return 0 ;
88   }
89   fd_close(p[0]) ;
90   if (p[1] == sizeof(e))
91   {
92     wait_pid(pid, &p[0]) ;
93     errno = e ;
94     return 0 ;
95   }
96   return pid ;
97 }
98 
99 #endif
100