Each time the fork () function is called, both the parent thread and the created child thread are executed from the fork ()

Source: Internet
Author: User

Linux under How many "-" will be printed:
12345678 int main ( void &NBSP;&NBSP; int i; &NBSP;&NBSP; for (i=0;i<4;i++) { &NBSP;&NBSP; fork (); &NBSP;&NBSP; printf ( &NBSP; } &NBSP; return 0;

When I=0, the main process and the child processes it creates are printed '-', print 2 I=1, the previous two processes print '-', each process creates a new subprocess, a total of 4 '-' i=2, the previous four processes print '-', and create a new sub-process, so the total printing of 8 '-' i=3, The previous 8 processes print '-', and create new sub-processes, so print a total of 16 '-' to sum up, the total print 2+4+8+16=30 each call fork () function, the parent thread and the created child threads are executed from fork (), means that the parent and child threads will perform the printf once, respectively. So the 1-time fork () call corresponds to 2 printf () calls corresponding to the creation of 1 child threads i = 4 o'clock, altogether creating a 2^4-1 child thread, that is, 15 fork () calls, so the call is 30 times printfhttps://www.nowcoder.co m/questionterminal/9b52b1a86ae64daab81f609f3a86c02f

Each time the fork () function is called, both the parent thread and the created child thread are executed from the fork ()

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.