about summary refs log tree commit diff
path: root/src/libenvexec/child_spawn.c
blob: 164f1b2fef978859e98fe0ab7d3ee8857a2f4a21 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* ISC license. */

#include <string.h>
#include <unistd.h>

#include <skalibs/types.h>
#include <skalibs/djbunix.h>
#include <skalibs/env.h>
#include <skalibs/cspawn.h>

pid_t child_spawn (char const *prog, char const *const *argv, char const *const *envp, int *fds, size_t n)
{
  pid_t pid ;
  cspawn_fileaction fa[2] =
  {
    [0] = { .type = CSPAWN_FA_MOVE, .x = { .fd2 = { [0] = 1 } } },
    [1] = { .type = CSPAWN_FA_MOVE, .x = { .fd2 = { [0] = 0 } } }
  } ;
  size_t m = sizeof(SKALIBS_CHILD_SPAWN_FDS_ENVVAR) ;
  size_t envlen = env_len(envp) ;
  size_t i = 0 ;
  int p[n ? n : 1][2] ;
  char const *newenv[envlen + 2] ;
  char modifs[m + 1 + n * UINT_FMT] ;

  for (; i < n ; i++)
  {
    if (pipe(p[i]) == -1) goto errpi ;
    if ((ndelay_on(p[i][i & 1]) == -1) || (coe(p[i][i & 1]) == -1)) goto errpip ;
  }

  memcpy(modifs, SKALIBS_CHILD_SPAWN_FDS_ENVVAR "=", sizeof(SKALIBS_CHILD_SPAWN_FDS_ENVVAR)) ;
  for (i = 2 ; i < n ; i++)
  {
    m += uint_fmt(modifs + m, p[i][!(i & 1)]) ;
    if (i+1 < n) modifs[m++] = ',' ;
  }
  modifs[m++] = 0 ;
  env_mergen(newenv, envlen + 2, envp, envlen, modifs, m, 1) ;
  if (n) fa[0].x.fd2[1] = p[0][1] ;
  if (n >= 2) fa[1].x.fd2[1] = p[1][0] ;
  pid = cspawn(prog, argv, newenv, CSPAWN_FLAGS_SIGBLOCKNONE, fa, n < 2 ? n : 2) ;
  if (!pid) goto errpi ;

  for (i = 0 ; i < n ; i++)
  {
    fd_close(p[i][!(i & 1)]) ;
    fds[i] = p[i][i & 1] ;
  }
  return pid ;

 errpip:
  i++ ;
 errpi:
  while (i--)
  {
    fd_close(p[i][1]) ;
    fd_close(p[i][0]) ;
  }
  return 0 ;
}