Linux System Programming 36 Process Control-The death of a process and the release of resources wait()/waitpid()

The previous section said that the parent process needs to deal with the aftermath of the child process, how to deal with the aftermath? Just wait() / waitpid()

Here is just a simple use of wait()

The use of waitpid() and various judgment termination status macros need to be studied


NAME
wait, waitpid, waitid-wait for process to change state

SYNOPSIS
#include <sys/types.h>
#include <sys/wait.h>

   pid_t wait(int *status);

   pid_t waitpid(pid_t pid, int *status, int options);

   int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options);

Of VALUE the RETURN
the wait ():. Success ON, Returns The Process The ID of Child terminated; ON error, -1 IS returned
successfully returns the process terminates the child process ID, failure -1

Insert picture description here
wait uses:

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

#define LEFT 200
#define RIGHT 250

int main(void)
{
	int i,j,mark;
	pid_t pid;
	
	for(i = LEFT; i <= RIGHT; i++)
	{
		pid = fork();
		if(pid < 0)
		{
			fprintf(stderr,"fork() failed!\n");
			exit(1);
		}
		else if(pid == 0)//child
		{
			mark = 1;
			for(j = 2; j < i/2; j++)
			{
				if(i % j ==0)
					{
						mark = 0;
						break;
					}
			
			}

			if(mark)
				printf("%d is a primer\n",i);

			exit(0);//!!!
		}
		
	}
	sleep(1000);
	exit(0);
}

At this time 201 child processes are dead processes and the parent process is init

Insert picture description here

After adding wait() aftermath:

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

#define LEFT 200
#define RIGHT 250

int main(void)
{
	int i,j,mark;
	pid_t pid;
	
	for(i = LEFT; i <= RIGHT; i++)
	{
		pid = fork();
		if(pid < 0)
		{
			fprintf(stderr,"fork() failed!\n");
			exit(1);
		}
		else if(pid == 0)//child
		{
			mark = 1;
			for(j = 2; j < i/2; j++)
			{
				if(i % j ==0)
					{
						mark = 0;
						break;
					}
			
			}

			if(mark)
				printf("%d is a primer\n",i);

			exit(0);//!!!
		}
		
	}

	for(i = LEFT;i <= 250; i++)
		wait(NULL);

	sleep(1000);
	exit(0);
}

At this point, ps axf has no child process that becomes a zombie process, only one parent process is left.

Guess you like

Origin blog.csdn.net/LinuxArmbiggod/article/details/113795396