1

when writing a daemon program, it is required to create a new session for it.

for example:

 fork a child process
 exit main process
 call setsid in child process

I am wondering why we need to create a new session for it? we can put it to the background by

$myserver&

Thanks

camino
  • 10,085
  • 20
  • 64
  • 115

1 Answers1

3

When you launch a program in background in xterm, with myprog &, the program will be killed when you close xterm without the command exit. Creating a new session may solve this pb (the process was a child process of xterm, and when you create a new session he is not a child process of xterm. you can close xterm without exit, the program will still be running).

man 2 setsid gives:

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. 

The process group ID and session ID of the calling process are set to the PID of 
the calling process.

The calling process will be the only process in this new process group and in 
this new session.

The example I gave you with xterm is justified by has no controlling terminal.

  • why xterm will kill the background process? – camino Nov 02 '13 at 21:15
  • When a parent process is killed, its child process are too. I read `man exit` in order to find the justification. – Pierre Emmanuel Lallemant Nov 02 '13 at 21:17
  • 1
    In fact, when we close a terminal with `exit`, the signal `SIGHUP` is sent to each child of the terminal (each program launched with this terminal, which didn't change their session). Normally, the child will exit too, but if the child process catch and treat this signal it could change its session. – Pierre Emmanuel Lallemant Nov 02 '13 at 21:25
  • 1
    I test it again, it can be reproduce in gnome terminal. when close the terminal window directly(not by the exit command) the background process will receive the signal SIGHUP, Thanks! But I still find some official documents about this. – camino Nov 03 '13 at 00:07