Linux for Loop Fork () produces child processes

Source: Internet
Author: User

#include <sys/types.h>

#include <unistd.h>

#include <stdio.h>

int main ()
{
for (int i = 0; i < 3; i + +)
{
int pid = fork ();
if (PID = = 0)
{
printf ("child\n");
}
Else
{
printf ("father\n");
}
}
return 0;
}

What is the result of the output, please?

At first glance, it is assumed that the result is 3 to Child-father, only the order is uncertain, and according to advanced programming in the UNIX environment, it is possible that the content of the two outputs may appear to be mixed with each other in extreme cases.

However, on the UNIX test, the discovery output has 7 pairs of child-father.

1.i=0, the parent process enters a for loop, at this time due to the role of fork, the father and son two processes (recorded as F0/S0), respectively, output father and child, and then the two to execute the subsequent code, then what is the subsequent code? Return 0? Due to the existence of the For loop, the subsequent code is the add instruction and a jump instruction, so the parent-child process will enter the I=1 case;

2.i=1, the parent process continues to be divided into two processes (F1/S1, respectively), and the child processes that fork out i=0 are divided into two processes (recorded as fs01/ss01 respectively), and then all of these processes enter i=2;

3 ... the process is similar to the above, there is no need to say more, believe that everything has been understood, according to the above marking method, i=2 will produce f2/s2,fs12/ss12,ffs012/sfs012,fss012/sss012.

Therefore, the final result is output of 7 to Child/father. The corresponding mathematical formula is:
1 + 2 + 4 + ... + 2^ (n-1) = 2^n-1

But then again, the use of fork in the For loop is not worth recommending, research and research can be, the actual application will cause a lot of trouble, need to be cautious.

Linux for Loop Fork () produces child processes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.