What is setsid ?

From my last post, I encountered this foreign new console command setsid. What the heck is setsid ? Manual page said this program let you "run a program in a new session". Why we need it? Because you want any program (e.g. daemon) that started from a terminal emulator (e.g. xterm), to stay running even after you close the terminal emulator.

Let's illustrate this using two simple examples.

1. Start xterm and later gedit editor.
$ xterm
$ gedit

2. Open up another terminal session and see the process tree. Notice that the xterm is the parent process of gedit. If we kill the parent process (xterm), all subsequent child processes will be terminated as well.
$ pstree | grep xterm

3. Close the xterm program. You will notice the gedit editor program will be shutdown as well.

Let's repeat step 1 - 3 but using setsid instead.

1. Again, start your xterm and later gedit editor using setsid. You will notice after the second command, you can proceed with other command as well.
$ xterm
$ setsid gedit

2. Let's find the process tree again. Notice gedit is not attached to the xterm parent process but instead a new process or a new session.
$ pstree | grep xterm

$ pstree | grep gedit

3. Close the xterm program. You'll notice gedit will still running.

Note that is not the same as forking a process using ampersand (&), running command below does not create a new session but a subshell child process
$ xterm
$ gedit &
$ pstree | grep xterm

Today I realized that after using GNU/Linux for so long, there are still a lot to be learned and explored. But yet so little time.

No comments:

Post a Comment