How do I run a program in daemon mode?
A program running in daemon mode has nothing to do with the console during its operation, that is, it is not affected by the console signal. It continues to run after the console exits, and other non-daemon programs will be affected by console operations, and is forcibly exited when the console exits. Therefore, most network service programs run in daemon mode.
You can add the following statement during program initialization, and the program will run in daemon mode:/** // * generate a new process and exit the original main process */
If (Fork () Exit (0 );
/** // * Close console handles such as stdin, stdout, and stderr */
For (n = 0; n <3; n ++) Close (N );
/** // * Point stdin, stdout, and stderr to/dev/null */
Open ("/dev/null", o_rdonly );
Dup2 (0, 1 );
Dup2 (0, 2 );
/** // * Set tty I/O attributes */
If (n = open ("/dev/tty", o_rdwr)> 0 )...{
IOCTL (n, tiocnotty, 0 );
Close (N );
}
/** // * Create a new session to make the current process a leader of process greoup */
Setsid ();
/** // * Generate a new process and exit the generated process. The new process has run in daemon mode */
If (Fork () Exit (0 );