Basic usage of the fork function in Linux

Source: Internet
Author: User

Code:

1#include <iostream>2#include <string>3#include <cstdio>4#include <unistd.h>5#include <sys/wait.h>6 7 using namespacestd;8 9 intMainintargcChar*argv[]) {Ten  One pid_t pid; A      for(inti =0; I <1; i++){ -cout<<"fork!"; -PID =fork (); the         if(PID = =0){ -cout<<"I am Child, my PID is"<<getpid () <<Endl; -}Else{ -cout<<"I am Father, my pid is"<<getpid () <<Endl; + Wait (NULL); -         } +     } A      at     return 0; -}

Output:

fork! I am Father, my pid is 7499fork! I am Child, my PID is 7500

If the 13th line of the procedure is replaced

cout<<"fork! "<<endl;

The output becomes

fork! I am Father, my pid is 7360I am child, my PID is 7361

Analysis:

The cout is first entered into the buffer (no direct output to the screen) and the buffer is copied after the fork is executed. Add the Endl will be directly output, you can see Endl has the role of line and empty.

Basic usage of the fork function in Linux

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.