The relationship between the child and parent processes of the operating system

The relationship between the child process of the operating system and the parent process (fork() function)

Use the unistd.h header file in linux to discuss the child and parent processes:

unistd.h is a header file in C++ that provides access to the POSIX operating system API.
The fork() function can create a child process of the current process, copy the data and stack space of the parent process, and inherit the code of the parent process, Resources, etc.
fork only executes the code after the return value, and returns the value twice, once to the parent process with the value pid of the child process, and the other time to the current process with the value 0.

Take the following code as an example (compilation tool: http://www.dooccn.com/c/):

1. How many HELLOs are output?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main () {
    
    
fork();
fork();
printf("HELLO\n");
}


Why does the running result not loop infinitely? As above, fork only executes the code after the return value, so the child process will not call the fork function again, but returns the value twice, so it will output 4 times. HELLO
analyzes the second fork first. After creating the child process, returns the pid to the parent The process also returns 0 to the child process, so printf("HELLO\n") will be executed twice; in the same way, after the first fork is executed, the next two lines of code will be executed twice, and the next two lines of code will be executed again Execute printf("HELLO\n") twice, so printf("HELLO\n") is executed four times;

2. What value is returned?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main () {
    
    
int pid;
pid=fork();
if(pid==0)
printf("子进程:pid=%d\n",pid);
else
printf("父进程:pid=%d\n",pid);
}

Running results
Insert picture description here
After testing, the starting value of pid is 12, if you continue to call fork, pid will increase

3. Who is the child process and the parent process?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main () {
    
    
int pid;
pid=fork();
for(int i=0;i<20;++i)
{
    
    
if(pid==0)
printf("子进程,i=%d\n",i);
else
printf("父进程,i=%d\n",i);
}
}

The result of the operation (with line breaks removed) is

for display purposes without line breaks . It can be seen from the results that if the parent process is first and the child process is followed, if the parent and child processes are synchronized, then the parent and child processes should interleave output. In fact, the parent process outputs the output before the child process is finished, so it is not synchronized. Can increase the number of cycles to verify.

Guess you like

Origin blog.csdn.net/weixin_42419611/article/details/104648572