Why fork () twice when unmounting?

I was looking for why people call twice fork()

and why the first call is made before setsid()

.

Yes, no new session is created if the caller is already the leader of the process group. But what if I just don't make the (great) parent the leader of the process group? Who will do it for me (without asking me)? (OK, maybe 1llum1n4t1, Sc13nt0l0gy, NSA, ...;))

Yes, the 1st child must exit immediately so as not to create a zombie process. But couldn't the (great) parent just get out after forking? Or will there be one or two calls fprintf(stderr,...

or write(2,...

(like "successfully started daemon xy") is such a big deal? (And couldn't I have prevented the zombies in another way?)

In general, does this double fork()

- "magic" (to avoid a problem) be required ? Or is it just tradition or so called "best practice" (eg avoid goto

)? Or is it just guaranteeing daemons work on "historical" (of course, I mean "too old to use in production environments") platforms like SVr4, BSD 3, RHEL 2, or some crappy 32-bit builtins?

+3


source to share


1 answer


The first call fork(2)

ensures that the process is not the group leader, so that the process can create a new session and become the session leader. There are other reasons for the former fork(2)

: if the daemon was started as a shell command, having a fork process and parent exit causes the shell to return to the prompt and wait for more commands.

The second is fork(2)

to ensure that the new process is not the session leader, so it cannot (accidentally) allocate a controlling terminal, since daemons should never have a controlling terminal. On the second fork, here's a quote from Advanced UNIX Programming, Chapter 13 (Daemon Processes):



On System V based systems, some people recommend calling fork again at this point, terminating the parent and continuing the daemon into the child. This ensures that the daemon is not the leader of the session, which prevents it from acquiring a control terminal under System V Rules. Alternatively, to avoid acquiring a control terminal, be sure to specify O_NOCTTY when opening the terminal device.

Section 13.3 of this book describes many more rules and patterns that are used to demonstrate the process, so it's worth taking the time to read it if you can.

+8


source







All Articles