When is setsid() useful, or why do we need to group processes in Linux?

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.

Tags:

Linux

C

Gcc

Sid