Linux System Programming 39 Process Control-Brief Analysis of Command Implementation

When a command is executed in the shell environment, it is actually that fork() spawns a child process (also a shell), the child process (also a shell) and then execl, the child process is transformed into an executable binary program that we need to execute , Such as ls etc. While the child process is running, the parent process waits for the child process resources in wait().

Such as the ls command, it must be the ls command, after the carriage return, the result of ls must be displayed first, and then the command line will pop up again

Review: Find prime numbers

#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);//!!!
		}
		
	}
	exit(0);
}


mhr@ubuntu:~/Desktop/xitongbiancheng/test$ gcc wait.c 
mhr@ubuntu:~/Desktop/xitongbiancheng/test$ ./a.out 
mhr@ubuntu:~/Desktop/xitongbiancheng/test$ 211 is a primer
223 is a primer
227 is a primer
229 is a primer
233 is a primer
239 is a primer
241 is a primer
^C
mhr@ubuntu:~/Desktop/xitongbiancheng/test$ 

Looking at the running results, it is found that when running ./a.out, the command line must be printed out first, and then the output result.

The shell creates a child process, and the child process execl() is transformed into a.out running, and there is no wait() aftermath in a.out, so this a.out fork() immediately executes exit() to exit. Then the current shell, as the parent process of a.out, is waiting() to collect the corpses, so as soon as a.out exits, the shell will immediately collect the corpses and end the printing command line. At this time, the child process from a.out fork() has become a dead process and is still running output.

So the question is: why is the display result of the child process also displayed on the current command line terminal at this time? Why not just open a terminal for output? That is, why do the parent and child processes share a terminal's information?

Because the file descriptor information in the file descriptor table of the parent process is copied to the child process, the file descriptor information of the two processes is the same. That is, the standard output objects are the same, so the parent and child processes will share a terminal terminal information.

Guess you like

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