Zombie Process: In the case of a child process does not exit, the parent process exits, the child process is taken over by the Init process, but the child process will not exit normally, and will not be withdrawn after the process's resources, so this situation should be avoided, Otherwise, the system resources will be consumed. To avoid this, you can use the Vfork function to derive from a child process, or a function in the parent process to wait for the child process to exit:
Header Files <sys/types.h><sys/wait.h>
int wait (int *status);//suspend execution of the current process until a signal is activated or the child process finishes executing
int waitpid (int pid,int *status,int options);
Wait for the PID to represent the completion of the execution of the child process, PID =-1, equivalent to wait. Wait for any child process
---------------------------------------------------------------------------------------------------------
Daemon: has been running in the background, the parent process is init, and the zombie process is similar, the difference is that the daemon is more of a service process, it is necessary to always provide services so can not quit.
General authoring steps for Daemons:
- Detach the control terminal (parent process) to make the parent process init
- Prohibit process from reopening control terminal
- Close file descriptor (inherits file descriptor from parent process, preferably close first, avoids unnecessary waste of system resources)
- Change Working directory (avoid working directory being uninstalled)
- Resetting the file creation mask (avoid the permissions and permissions we need when creating the file)
- int c = 0;
- int pid = fork ();
- if (PID > 0) {//exit parent process to make its parent process init
- Exit (0);
- }
- if (PID < 0) {//child process creation failed to exit
- Exit (1);
- }
- for (; c < 101122;c++) {//Close file descriptor
- Close (c);
- }
- ChDir ("/"); Change Working directory
- Umask (0); Reset File Creation Mask
- while (1) {//Dead loop keeps it running in the background
- The work required to prepare the process
- }
Daemon and Zombie Processes