Child process Asynchronous cleanup
SIGCHLD signal: When a child process terminates, it is automatically sent to the parent process, writes this signal processing routine, asynchronously clears the child process
#include <signal.h>#include<string.h>#include<sys/types.h>#include<sys/wait.h>sig_atomic_t child_exit_status;extern "C"{ voidCleanUp (intsig_num) { intstatus; Wait (&status);//Clear Child processChild_exit_status = status;//Store the state of a child process }}intMain () {//Handling SIGCHLD Signals structsigaction sa; memset (&sa,0,sizeof(SA)); Sa.sa_handler= &CleanUp; Sigaction (SIGCHLD,&SA, NULL); //the normal processing code is here, such as calling fork () to create a child process return 0;}
Steps to create a daemon
- Create a new process: The new process will be the future daemon
- The daemon's parent process exits: Ensure that the grandparent process confirms that the parent process has ended, and that the daemon is not the leader process
- The daemon creates a new process group and session: and becomes the first process for both, at which point the newly created session has no associated control terminal
- Change the working directory: The daemon normally starts with the system, and the working directory should not continue to use the inherited working directory
- Reset file Permission mask: Do not need to inherit file permission mask
- Close all file descriptors: No need to inherit any open file descriptors
- Callout Flow redirection to/dev/null
#include <sys/types.h>#include<sys/stat.h>#include<stdlib.h>#include<stdio.h>#include<fcntl.h>#include<unistd.h>#include<linux/fs.h>intMain () {pid_t PID=Fork (); if(PID = =-1) { return-1; } Else if(PID! =0) exit (exit_success); //Child Process if(Setsid () = =-1) return-2; //set up working directory if(ChDir ("/") == -1) return-3; //Reset file Permission MaskUmask0); //Close File Descriptor for(inti =0; I <3; i++) Close (i); //REDIRECT Standard streamOpen"/dev/null", O_RDWR); DUP (0); DUP (0); //the actual working code of the daemon is here return 0;}
Daemon creation Function Daemon ()
Implement these functions to reduce the burden of writing daemons
C + + Learning Note 42: Process Management