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. Return zero on
success, or raise one of Errno::*.
static VALUE
proc_daemon(int argc, VALUE *argv)
{
VALUE nochdir, noclose;
int n;
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:
rb_sys_fail("daemon");
case 0:
break;
default:
_exit(EXIT_SUCCESS);
}
proc_setsid();
/* must not be process-leader */
switch (rb_fork(0, 0, 0, Qnil)) {
case -1:
rb_sys_fail("daemon");
case 0:
break;
default:
_exit(EXIT_SUCCESS);
}
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);
#endif
}