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?
We can use the & operator, and the nohup, disown, setsid, and screen commands to start a process detached from the terminal. However, to detach a process that has already started, we need to use the bg command after pausing the process using Ctrl+Z.
A daemon is also called background processes. It is a UNIX or Linux program that executes inside the background. Almost every daemon contains names that finish with "d" the letter. For example, sshd, this manages connections of SSH remote access, or the httpd daemon that manages the Apache server.
To create a daemon, you need a background process whose parent process is init. In the code above, _daemon creates a child process and then kills the parent process. In this case, your new process will be a subprocess of init and will continue to run in the background.
The word daemon for denoting a background program is from the Unix culture; it is not universal. A service is a program which responds to requests from other programs over some inter-process communication mechanism (usually over a network). A service is what a server provides.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With