Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why MUST detach from tty when writing a linux daemon?

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?

like image 624
OriginalWood Avatar asked Jan 08 '12 12:01

OriginalWood


People also ask

How do I detach a command in Linux?

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.

How does Linux daemon work?

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.

How do I run a daemon process in Linux?

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.

What is the difference between service and daemon in Linux?

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.


1 Answers

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.

like image 58
Adam Zalcman Avatar answered Oct 05 '22 16:10

Adam Zalcman