Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

linux

gcc

sid

I've tried man(3) setsid, but it only explains how to use it, I don't quiet understand when is setsid useful?

like image 866
daisy Avatar asked Jun 20 '12 13:06

daisy


People also ask

What is Setsid used for?

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.

What is the significance of Setsid () in Daemonizing a process?

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.

What is process group Linux?

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.


2 Answers

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.

like image 148
AProgrammer Avatar answered Sep 28 '22 02:09

AProgrammer


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.

like image 37
William Pursell Avatar answered Sep 28 '22 02:09

William Pursell