Detach the process from controlling terminal and run in the background as
system daemon. Unless the
argument nochdir is true (i.e. non false), it changes the current working
directory to the root (“/”). Unless the argument noclose is true, daemon() will redirect standard
input, standard output and standard error to /dev/null.
static VALUE
proc_daemon(int argc, VALUE *argv)
{
VALUE nochdir, noclose;
#if defined(HAVE_DAEMON) || defined(HAVE_FORK)
int n;
#endif
rb_secure(2);
rb_scan_args(argc, argv, "02", &nochdir, &noclose);
#if defined(HAVE_DAEMON)
prefork();
before_fork();
n = daemon(RTEST(nochdir), RTEST(noclose));
after_fork();
if (n < 0) rb_sys_fail("daemon");
return INT2FIX(n);
#elif defined(HAVE_FORK)
switch (rb_fork(0, 0, 0, Qnil)) {
case -1:
return INT2FIX(-1);
case 0:
break;
default:
_exit(0);
}
proc_setsid();
/* must not be process-leader */
switch (rb_fork(0, 0, 0, Qnil)) {
case -1:
return INT2FIX(-1);
case 0:
break;
default:
_exit(0);
}
if (!RTEST(nochdir))
(void)chdir("/");
if (!RTEST(noclose) && (n = open("/dev/null", O_RDWR, 0)) != -1) {
(void)dup2(n, 0);
(void)dup2(n, 1);
(void)dup2(n, 2);
if (n > 2)
(void)close (n);
}
return INT2FIX(0);
#else
rb_notimplement();
#endif
}