1 /* ISC license. */
2 
3 #include <unistd.h>
4 #include <sys/resource.h>
5 
6 #include <skalibs/types.h>
7 #include <skalibs/strerr2.h>
8 #include <skalibs/djbunix.h>
9 #include <skalibs/exec.h>
10 
11 #define USAGE "fdreserve n prog..."
12 
13 #define MAXFDS 1024
14 
doit(char * modif,unsigned int i,int fd)15 unsigned int doit (char *modif, unsigned int i, int fd)
16 {
17   unsigned int pos = 2 ;
18   modif[0] = 'F' ; modif[1] = 'D' ;
19   pos += uint_fmt(modif + pos, i) ;
20   modif[pos++] = '=' ;
21   pos += uint_fmt(modif + pos, (unsigned int)fd) ;
22   modif[pos++] = 0 ;
23   return pos ;
24 }
25 
main(int argc,char const * const * argv)26 int main (int argc, char const *const *argv)
27 {
28   unsigned int n ;
29   PROG = "fdreserve" ;
30   if ((argc < 3) || !uint0_scan(argv[1], &n))
31     strerr_dieusage(100, USAGE) ;
32   {
33     struct rlimit lim ;
34     if (getrlimit(RLIMIT_NOFILE, &lim) < 0) strerr_diefu1sys(111, "getrlimit") ;
35     if (n > lim.rlim_cur) strerr_dief1x(100, "too many requested fds") ;
36   }
37   {
38     char modif[12 * n] ;  /* enough for n times "FDaaaa=bbbb\0" */
39     unsigned int j = 0 ;
40     {
41       int fd[n >> 1][2] ;
42       unsigned int i = 0 ;
43       for (; i < (n>>1) ; i++)
44         if (pipe(fd[i]) < 0)
45           strerr_diefu1sys(111, "reserve fds") ;
46       if (n & 1)
47       {
48         int lastfd = openb_read("/dev/null") ;
49         if (lastfd < 0)
50           strerr_diefu1sys(111, "reserve last fd") ;
51         fd_close(lastfd) ;
52         j += doit(modif + j, n-1, lastfd) ;
53       }
54       for (i = 0 ; i < (n>>1) ; i++)
55       {
56         fd_close(fd[i][0]) ;
57         fd_close(fd[i][1]) ;
58         j += doit(modif + j, i<<1, fd[i][0]) ;
59         j += doit(modif + j, (i<<1)|1, fd[i][1]) ;
60       }
61     }
62     xmexec_n(argv+2, modif, j, n) ;
63   }
64 }
65