Understanding Zombie Processes under linux-Orphan Processes-Test Samples and Sources for Daemons

Keywords: C C++ Linux multiple processes Process

Test Code

#define _GNU_SOURCE

#include<sched.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdint.h>
#include<sys/wait.h>
#include<sys/types.h>

typedef void (*spawn_proc_pt)(void*data);

static void work_process_cycle(void*data);//Function of work
static void start_processes(int n);		  //Several people work

pid_t spawn_process(spawn_proc_pt proc,void *data,char *name);	//Attributes of each job


int main(int argc,char** argv){
	
	printf("father pid:%d\n",getpid());
	
	start_processes(2);

//	printf("father is over!\n");	
	//wait(NULL);
	
	while(1) sleep(10);	
	return 0;	
}

void start_processes(int n){
	
	int i =0;
	for(i=n-1;i>=0;i--){
		
		spawn_process(work_process_cycle,(void*)(intptr_t)i,"Work process");
	}
	
}

pid_t spawn_process(spawn_proc_pt proc,void *data,char *name){
	
	//Only child processes get work
	
	pid_t pid;
	
	pid = fork();
	
	
	switch(pid){
		
	case -1:
		fprintf(stderr,"fork() failed while spawning\"%s\"\n",name);
		return -1;
	case 0:
		proc(data);
		return 0;
	default :
		//Parent process does not work
		break;
		
	}
	
	printf("start pid:%ld name:%s\n",(long int)pid,name);
	
	return pid;
	
}

void work_process_init(int worker){
	cpu_set_t cpu_affinity;
	
	CPU_ZERO(&cpu_affinity); //Zero
	CPU_SET(worker%CPU_SETSIZE,&cpu_affinity);//binding

	if(stderr,sched_setaffinity(0,sizeof(cpu_set_t),&cpu_affinity)==-1){
		
		fprintf(stderr,"sched_setaffinity failed\n");
	}
}

void work_process_cycle(void *data){
	//Bind before work
	int worker = (intptr_t)data;
	
	work_process_init(worker);
	
	for(;;){
		sleep(10);
		printf("get pid:%ld...\n",(long int)getpid());
		
	}
	
}

orphan

Orphan processes: If a parent process exits and one or more of its child processes are still running, those child processes will become orphan processes. The orphan processes will be adopted by the init process and the init process will complete the status collection on them.

Orphan Process Test demo

Let's create a parent process and two child processes, and let the program run related processes using linux to see the commands. Understand the following test cases to understand the concepts of processes

After compiling and running the above code, guer.exe is the program we're going to test and we see that the program started with parent process number 2004 and created two sub-processes, 2005 and 2006, respectively.

Use the command ps_ef|grep guer.exer to view the process id numbers of the corresponding parent and child processes in the re-system when opening a terminal with MobaXterm Personal Edition

Kill the parent process using the command kill-9 2003, and then use ps _ef|grep guer.exer to view the process. After killing the parent process again in 2003, the process id of the parent process id of 2004 and 2005 changed to 1, which represents the init process. We call it "Grandpa process"When the father of the more natural child left, Grandpa took over the care of the child.

Zombie

**Zombie Process: ** When a process calls the exit command to end its life, it is not actually destroyed, but rather leaves behind a data structure called Zombie (the system calls exit to exit a process, but only to turn a normal process into a zombie process, which cannot be completely destroyed).
_In the state of a Linux process, a zombie process is a very special kind of process. It has given up almost all memory space, has no executable code, and cannot be scheduled. It just keeps a place in the process list, records the exit status of the process and other information for other processes to collect. In addition, the zombie process no longer occupies any memory space.Its parent process will kill it if it does not have a SIGCHLD signal processing function called wait or waitpid() Waiting for the child process to end without explicitly ignoring the signal keeps it zombie. If the parent process ends, the init process automatically takes over the child process and collects the body for it, and it can be cleaned up. But if the parent process is a loop and does not end, the child process will remain zombie all the time, which isWhy are there so many zombie processes in the system at times?

Zombie Process Test demo

The test code uses the same c-file code as the orphan process, recompiles it as an executable of jianshi.exe, executes it, and creates parent process id number 2266 child process id number 2267 2268

Use the command ps-ef|grep jianshi.exe to view the process id number

The process executes normally, killing the child process with kill-9 2267 2268, when it finds that the last occurrence of the child process number means a zombie process

Use kill-9 2266 to kill the parent process and look at the related processes. When the parent process is killed, go on=="Collect the corpse"== to see that all parent and child processes have been killed

Daemon

Daemons: Processes that are not associated with any terminal, usually running at system startup as root or other special users (apache and postfix) Runs and handles some system-level tasks. A daemon is disconnected from a terminal to avoid displaying information on any terminal during execution, and the process is not interrupted by terminal information generated by any terminal (such as closing the terminal). How can it become a daemon? The steps are as follows:
1. Call fork() to create a new process, which will be the future daemon.
2. Call exit in the parent process to ensure that the child process is not the process group leader
3. Call setsid() to create a new session area
4. Change the current directory to the root directory (if you use the current directory as the daemon's directory, the current directory cannot be uninstalled as the daemon's working directory)
5. Redirect standard input, standard output, standard error to/dev/null.

Daemon test demo

Process daemon is implemented using interface API

int daemon(int nochdir, int noclose)
{
    int fd;

    switch (fork()) {
    case -1:
        return (-1);
    case 0:
        break;
    default:
        _exit(0);
    }

    if (setsid() == -1)
        return (-1);

    if (!nochdir)
        (void)chdir("/");

    if (!noclose && (fd = open("/dev/null", O_RDWR, 0)) != -1) {
        (void)dup2(fd, STDIN_FILENO);
        (void)dup2(fd, STDOUT_FILENO);
        (void)dup2(fd, STDERR_FILENO);
        if (fd > 2)
            (void)close (fd);
    }
    return (0);
}

You only need to call daemon when using it, and pass in parameters (0,0)

Running the program cp.exe found that the printf printed characters in the program did not appear on the terminal

We open another terminal to see if the process cp.exe exists and find that the process id does exist, indicating that the process is running

Let's kill this process using killall -9 cp.exe. See if the process can be killed

Summary: The orphan process is the child process after the death of the parent process before the child process. The grandfather process with thread id number 1 hosts the orphan process. The zombie process is that the child process dies before the parent process. After the death, the child process becomes a zombie process, marked as a zombie process, and the parent process dies before the zombie process is collected.The daemon does not display the corresponding information on the terminal and runs silently in the background.This is generally the mode in which our servers are deployed. There are no terminals to output information to the log.

Posted by bogins on Thu, 30 Sep 2021 10:16:29 -0700