I've tried man(3) setsid
, but it only explains how to use it, I don't quiet understand when is setsid useful?
A session is a set of processes which shares a controlling terminal. setsid is useful when you want to start a new session, because you have started to be connected to a new terminal -- such as when starting a shell inside a terminal emulator -- or you want a daemon (which you don't want to be associated with a controlling terminal).
The best explanation I know of these aspect is in R.W. Stevens Advanced programming in the Unix environment.
Why do we need to group processes?
Consider the situation in which you wish to shut down cleanly, and that includes sending a signal to your children. There is an inherent race condition: a SIGCHLD has not been received, so you know that child is still alive. So you send a signal. But the child terminates before the signal is sent and another (unrelated) process starts up and gets the same pid as the child to which the signal was sent. The signal then goes to the new, unrelated process. This is bad. So, rather than sending a signal to specific pids, you signal the process group. When the child dies and a new process begins with the original pid, the new process is not part of the process group and the problem described above is avoided.
setsid
which creates a session leader, not just a process group. AFAIK there is no way to atomically signal an entire session). –
Dyspepsia kill
command with a job spec (like %1
) rather than a process ID, at least in Bash (maybe not in other shells; I don't know enough about them). But it's certainly easier just to signal the process group. –
Dyspepsia To know when it is useful, you have to compare it with other similar commands which daemonize a process:
screen: putting a process into the background, but the terminal still exists. So if you "fg " to bring the process into the foreground again, all its standard output will appear.
nohup: putting a process into background, but output all screen display to a file. So you just need to "cat" the file to see the output.
setsid: put a process into the background, but because its terminal is given up, there is no way to retrieve the output. Use this only if screen display is not important to you.
For other complication implicated on pid and behavior see this:
http://go2linux.garron.me/linux/2010/12/setsid-how-execute-commands-after-you-exit-shell-prompt-866/
© 2022 - 2024 — McMap. All rights reserved.
wait
orwaitpid
or similar. Thus if you send a termination signal and thenwaitpid
, there is no race condition. The only exception is you have set the SIGCHLD action to "ignore", in which case child processes may die off without requiring calls towait
. – Dyspepsia