skalibs

Mirror/fork of https://skarnet.org/software/skalibs/
git clone https://ccx.te2000.cz/git/skalibs
Log | Files | Refs | README | LICENSE

child_spawn.c (1525B)


      1 /* ISC license. */
      2 
      3 #include <string.h>
      4 #include <unistd.h>
      5 
      6 #include <skalibs/types.h>
      7 #include <skalibs/djbunix.h>
      8 #include <skalibs/env.h>
      9 #include <skalibs/cspawn.h>
     10 
     11 pid_t child_spawn (char const *prog, char const *const *argv, char const *const *envp, int *fds, size_t n)
     12 {
     13   pid_t pid ;
     14   cspawn_fileaction fa[2] =
     15   {
     16     [0] = { .type = CSPAWN_FA_MOVE, .x = { .fd2 = { [0] = 1 } } },
     17     [1] = { .type = CSPAWN_FA_MOVE, .x = { .fd2 = { [0] = 0 } } }
     18   } ;
     19   size_t m = sizeof(SKALIBS_CHILD_SPAWN_FDS_ENVVAR) ;
     20   size_t envlen = env_len(envp) ;
     21   size_t i = 0 ;
     22   int p[n ? n : 1][2] ;
     23   char const *newenv[envlen + 2] ;
     24   char modifs[m + 1 + n * UINT_FMT] ;
     25 
     26   for (; i < n ; i++)
     27   {
     28     if (pipe(p[i]) == -1) goto errpi ;
     29     if ((ndelay_on(p[i][i & 1]) == -1) || (coe(p[i][i & 1]) == -1)) goto errpip ;
     30   }
     31 
     32   memcpy(modifs, SKALIBS_CHILD_SPAWN_FDS_ENVVAR "=", sizeof(SKALIBS_CHILD_SPAWN_FDS_ENVVAR)) ;
     33   for (i = 2 ; i < n ; i++)
     34   {
     35     m += uint_fmt(modifs + m, p[i][!(i & 1)]) ;
     36     if (i+1 < n) modifs[m++] = ',' ;
     37   }
     38   modifs[m++] = 0 ;
     39   env_mergen(newenv, envlen + 2, envp, envlen, modifs, m, 1) ;
     40   if (n) fa[0].x.fd2[1] = p[0][1] ;
     41   if (n >= 2) fa[1].x.fd2[1] = p[1][0] ;
     42   pid = cspawn(prog, argv, newenv, CSPAWN_FLAGS_SIGBLOCKNONE, fa, n < 2 ? n : 2) ;
     43   if (!pid) goto errpi ;
     44 
     45   for (i = 0 ; i < n ; i++)
     46   {
     47     fd_close(p[i][!(i & 1)]) ;
     48     fds[i] = p[i][i & 1] ;
     49   }
     50   return pid ;
     51 
     52  errpip:
     53   i++ ;
     54  errpi:
     55   while (i--)
     56   {
     57     fd_close(p[i][1]) ;
     58     fd_close(p[i][0]) ;
     59   }
     60   return 0 ;
     61 }