I've tried man(3) setsid
, but it only explains how to use it, I don't quiet understand when is setsid useful?
setsid command in Linux system is used to run a program in a new session. The command will call the fork(2) if already a process group leader. Else, it will execute a program in the current process. Example: It will execute our shell script in a new session.
We use setsid() because if we just kill the parent the child will be killed too, the setsid() : creates a new session if the calling process is not a process group leader. The calling process is the leader of the new session, the process group leader of the new process group, and has no controlling terminal.
A process group in Linux, as the name suggests, is a way that Linux groups process together. They are a collection of related processes sharing the same PGID's (Process Group ID). A common misconception is that killing the parent process will kill the children's processes too.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With