When i tried to write a daemon under linux using C, i was told i should add following code after fork code block:
/* Preparations */
...
/* Fork a new process */
pid_t cpid = fork();
if (cpid == -1){perror("fork");exit(1);}
if (cpid > 0){exit(0);}
/* WHY detach from tty ? */
int fd = open("/dev/tty", O_RDWR);
ioctl(fd, TIOCNOTTY, NULL);
/* Why set PGID as current PID ? */
setpgid(getpid(), 0);
My question is: Is there a must to do the above operations?
You must disassociate your daemon process from the terminal to avoid being sent signals related to terminal's operation (like SIGHUP when the terminal session ends as well as potentially SIGTTIN and SIGTTOU).
Note however that the way of disassociating from the terminal using TIOCNOTTY ioctl
is largely obsolete. You should use setsid()
instead.
The reason for a daemon to leave its original process group is not to receive signals sent to that group. Note that setsid()
also places your process in its own process group.