[PATCH] bb_daemonize: double-fork to ensure child doesn't get controlling tty

Denys Vlasenko vda.linux at googlemail.com
Wed Nov 9 14:53:55 UTC 2011


On Mon, Nov 7, 2011 at 10:54 PM, Peter Korsgaard <jacmet at sunsite.dk> wrote:
> bb_daemonize should double-fork so it isn't a session leader, and hence
> doesn't get a controlling tty on Linux if a tty is ever opened, similar to
> how libdaemon's daemon_fork or the big start-stop-daemon does it.
>
> For details, see http://www.win.tue.nl/~aeb/linux/lk/lk-10.html#ss10.3

Yes, I know this.

Linux has its own fair share of quirks here.

For example, setsid() fails if the process is a process group leader
(which happens quite often: say, every time you run a program from
interactive shell). This makes sense, but if process group has no
other processes (also happens very often), setsid() does not have
to fail. But currently, in this situation it does fail.

> @@ -258,6 +258,8 @@ void FAST_FUNC bb_daemonize_or_rexec(int flags, char **argv)
>                dup2(fd, 0);
>                dup2(fd, 1);
>                dup2(fd, 2);
> +               if (fork_or_rexec(argv))
> +                       exit(EXIT_SUCCESS); /* parent */
>        }
>        while (fd > 2) {
>                close(fd--);

Fork is expensive. vfork+exec on NOMMU doubly so.
In many cases, callers know that they will never try open a tty.
Let's make this second fork_or_rexec() optional:

if (flags & DAEMON_DOUBLE_FORK) ...

-- 
vda


More information about the busybox mailing list