Create a daemon function:
Int daemon_init (void)
{
Int max_fd, RET;
Int iret;
Struct sigaction Act;
Int I;
If (iret = fork ()){
Printf ("An error occurred while creating the daemon! /N ");
_ Exit (4 );
}
Else if (iret! = 0)
{
_ Exit (0 );
}
The most critical step for else if (setsid () to create a daemon is to call the setsid function to create a new session and become the session leader.
{
_ Exit (5 );
}
/* Ignore the exit signal of the parent process */
Act. sa_handler = sig_ign;
Sigemptyset (& act. sa_mask );
// The sigemptyset function initializes the signal set pointed to by the set, so that the corresponding bits of all signals are cleared, indicating that the signal set does not contain any valid signal.
Act. sa_flags = 0;
Sigaction (sighup, & act, null );
// The sigaction function can read and modify the processing actions associated with the specified signal.
If (ret = fork ()){
_ Exit (4 );
}
Else if (Ret! = 0)
{
_ Exit (0 );
}
/* Change the process working path */
/* Printf ("pub74/N ");*/
/* Chdir ("/");*/
/* Printf ("pub76/N ");*/
Umask (0 );
Setpgrp ();
/* Open ("DEV/null", o_rdwr );*/
/* DUP (1 );
DUP (2); */DUP and dup2 can be used to copy an existing file descriptor so that the two file descriptors point to the same file struct.
Signal (sigchld, sig_ign );
Signal (sigpipe, sig_ign );
/* Set the signal. The parent process does not pre-Recycle the sub-process information to prevent zombie processes */
/* If the sigchld signal is set to sig_ign, the sub-process that calls the process is in the final state.
It does not become a zombie process. The Calling process does not have to wait for the sub-process to return and perform phase
Processing.
Add: if a process has been terminated, but its parent process has not called wait or waitpid to clean it up, the Process status is called Zombie process */
Return 0;
}