By using the code downloaded from the internet, the daemon process is successfully implemented. The original daemon process is very simple.
Execute in main Function
Init_daemon (); // initialize to Daemon
You can turn the process into a daemon process.
# Include
# Include
# Include
# Include
# Include
Void init_daemon (void)
{
Int pid;
Int I;
If (pid = fork ())
Exit (0); // It is the parent process and ends the parent process.
Else if (pid <0)
Exit (1); // fork failed, quit
// It is the first sub-process and continues execution in the background
Setsid (); // The first sub-process becomes the new session leader and process leader
// Separate it from the control terminal
If (pid = fork ())
Exit (0); // It is the first sub-process and ends the first sub-process.
Else if (pid <0)
Exit (1); // fork failed, quit
// The second sub-process. Continue
// The second sub-process is no longer the session leader
For (I = 0; I <NOFILE; ++ I) // close the opened file descriptor
Close (I );
Chdir ("/tmp"); // change the working directory to/tmp
Umask (0); // reset the file to create a mask
Return;
}