Daemon is a backend program that is invisible to users and runs secretly in the background.
The daemon does not need to communicate with the console. Therefore, you can disable standard input, standard output, and standard errors.
How to disable it?
This requirement can be achieved by calling the library function daemon,
# Include <unistd. h>
Int daemon (int nochdir, int noclose );
Inside the daemon function, it will turn off stdin, stdout, and stderr.
I personally think:
The so-called daemon process is just a concept. It is not necessarily a daemon function;
The daemon function is not a daemon process.
How does the daemon function close stdin, stdout, and stderr?
Redirects stdin, stdout, and stderr to the black hole file/dev/null.
Int fd = open ("/dev/null", O_RDWR, 0 );
Dup2 (fd, 0 );
Dup2 (fd, 1 );
Dup2 (fd, 2 );
Close (fd );
The system calls open to open a file and returns the file descriptor of the file,
# Include <sys/types. h>
# Include <sys/stat. h>
# Include <fcntl. h>
Int open (const char * pathname, int flags, mode_t mode );
The system calls close to close a specified file,
# Inlcude <unistd. h>
Int close (int fd );
The system calls dup2 to redirect the newfd file to oldfd.
These two file descriptors share the same data structure, so that operations on one of the files will affect the two files at the same time.
Newfd can be understood as a pointer pointing to the oldfd point, so that the operations on newfd and oldfd are the same.
# Include <unistd. h>
Int dup2 (int oldfd, int newfd );
The daemon that runs independently is called stand alone daemon. Common daemon include atd, crond, and syslogd.
The other opposite to stand alone daemon is super daemon.
For example, inetd listens to Network Ports in the background. When a request is received from the client, it listens
Decide to start different network service programs.
Another classification method is: signal control daemon and interval control daemon.
Like inetd, it belongs to signal control daemon; crond and syslogd belong to interval control daemon.
There are many daemon, such as dhcpd, httpd, and ntpd.
In this article, you should first understand it.