[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Clarification about bug #463538 is needed



"Sergei Golovan" <sgolovan@nes.ru> writes:

> Erlang does exactly the following when detaches from a terminal:
>
>  if (start_detached) {
>    int status = fork();
>    if (status != 0)
>      return 0;
>    status = fork();
>    if (status != 0)
>      return 0;
>
>    close(0);
>    open("/dev/null", O_RDONLY);
>    close(1);
>    open("/dev/null", O_WRONLY);
>    close(2);
>    open("/dev/null", O_WRONLY);
>  }
>  {
>    execv(emu, Eargsp); /* executing the main Erlang emulator */
>  }
>
> Is this behavior incorrect?

It's missing either setsid or ioctl("/dev/tty", TIOCNOTTY).  The
semi-standard daemon() function does the right thing.  Here's a public
domain replacement (which assumes you have an Autoconf probe for whether
setsid is available).  It depends on a wrapper around standard system
headers, but I expect you get the idea and could fix that.

/* $Id: daemon.c 4022 2008-03-31 06:11:07Z rra $
 *
 * Replacement for a missing daemon.
 *
 * Provides the same functionality as the library function daemon for those
 * systems that don't have it.
 *
 * Written by Russ Allbery <rra@stanford.edu>
 * This work is hereby placed in the public domain by its author.
 */

#include <config.h>
#include <portable/system.h>

#include <errno.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/stat.h>

int
daemon(int nochdir, int noclose)
{
    int status, fd;

    /*
     * Fork and exit in the parent to disassociate from the current process
     * group and become the leader of a new process group.
     */
    status = fork();
    if (status < 0)
        return -1;
    else if (status > 0)
        _exit(0);

    /*
     * setsid() should take care of disassociating from the controlling
     * terminal, and FreeBSD at least doesn't like TIOCNOTTY if you don't
     * already have a controlling terminal.  So only use the older TIOCNOTTY
     * method if setsid() isn't available.
     */
#if HAVE_SETSID
    if (setsid() < 0)
        return -1;
#elif defined(TIOCNOTTY)
    fd = open("/dev/tty", O_RDWR);
    if (fd >= 0) {
        if (ioctl(fd, TIOCNOTTY, NULL) < 0) {
            status = errno;
            close(fd);
            errno = status;
            return -1;
        }
        close(fd);
    }
#endif /* defined(TIOCNOTTY) */

    if (!nochdir && chdir("/") < 0)
        return -1;

    if (!noclose) {
        fd = open("/dev/null", O_RDWR, 0);
        if (fd < 0)
            return -1;
        else {
            if (dup2(fd, STDIN_FILENO) < 0)
                return -1;
            if (dup2(fd, STDOUT_FILENO) < 0)
                return -1;
            if (dup2(fd, STDERR_FILENO) < 0)
                return -1;
            if (fd > 2)
                close(fd);
        }
    }
    return 0;
}

-- 
Russ Allbery (rra@debian.org)               <http://www.eyrie.org/~eagle/>


Reply to: