s6

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

s6-setsid.c (1756B)


      1 /* ISC license. */
      2 
      3 #include <unistd.h>
      4 #include <signal.h>
      5 
      6 #include <skalibs/types.h>
      7 #include <skalibs/sgetopt.h>
      8 #include <skalibs/strerr.h>
      9 #include <skalibs/sig.h>
     10 #include <skalibs/exec.h>
     11 
     12 #define USAGE "s6-setsid [ -s | -b | -f | -g ] [ -i | -I | -q ] [ -d ctty ] prog..."
     13 #define dieusage() strerr_dieusage(100, USAGE)
     14 
     15 int main (int argc, char const *const *argv)
     16 {
     17   unsigned int ctty = 0, what = 0, insist = 1 ;
     18   PROG = "s6-setsid" ;
     19   {
     20     subgetopt l = SUBGETOPT_ZERO ;
     21     for (;;)
     22     {
     23       int opt = subgetopt_r(argc, argv, "sbfgiIqd:", &l) ;
     24       if (opt == -1) break ;
     25       switch (opt)
     26       {
     27         case 's' : what = 0 ; break ;
     28         case 'b' : what = 1 ; break ;
     29         case 'f' : what = 2 ; break ;
     30         case 'g' : what = 3 ; break ;
     31         case 'i' : insist = 2 ; break ;
     32         case 'I' : insist = 1 ; break ;
     33         case 'q' : insist = 0 ; break ;
     34         case 'd' : if (!uint0_scan(l.arg, &ctty)) dieusage() ; break ;
     35         default : dieusage() ;
     36       }
     37     }
     38     argc -= l.ind ; argv += l.ind ;
     39   }
     40   if (!argc) dieusage() ;
     41 
     42   if (what)
     43   {
     44     if (setpgid(0, 0) < 0) switch (insist)
     45     {
     46       case 2 : strerr_diefu1sys(111, "setpgid") ;
     47       case 1 : strerr_warnwu1sys("setpgid") ; break ;
     48       default : break ;
     49     }
     50 
     51     if (what >= 2)
     52     {
     53       if (what == 3) sig_altignore(SIGTTOU) ;
     54       if (tcsetpgrp(ctty, getpid()) < 0) switch (insist)
     55       {
     56         case 2 : strerr_diefu1sys(111, "tcsetpgrp") ;
     57         case 1 : strerr_warnwu1sys("tcsetpgrp") ; break ;
     58         default : break ;
     59       }
     60     }
     61   }
     62   else if (setsid() < 0) switch (insist)
     63   {
     64     case 2 : strerr_diefu1sys(111, "setsid") ;
     65     case 1 : strerr_warnwu1sys("setsid") ; break ;
     66     default : break ;
     67   }
     68 
     69   xexec(argv) ;
     70 }