Unix 的 fork 函数

fork函数可以创建一个和当前映像一样的子进程,这个函数会返回两个值:从子进程返回0,从父进程返回子进程的PID;

  • 1)在父进程中,fork返回新创建子进程的进程ID;
  • 2)在子进程中,fork返回0;
  • 3)如果出现错误,fork返回一个负值;
#include <iostream>
#include <unistd.h> 
using namespace std;

int main()
{
    pid_t fpid; //fpid表示fork函数返回的值  
    int count = 0;
    cout << &count << endl;   
    fpid = fork();   
    if (fpid < 0)   
        printf("error in fork!\n");   
    else if (fpid == 0) {  
        printf("i am the child process, my process id is %d\n",getpid());   
        cout << &count << endl; 
        count++;  
    }  
    else {  
        printf("i am the parent process, my process id is %d\n",getpid());  
        cout << &count << endl; 
        count++;  
    }  
    printf("统计结果是: %d\n",count); 
    
    return 0;
}

输出:

Start
0x7ffd3ed42530
i am the parent process, my process id is 22
0x7ffd3ed42530
统计结果是: 1
i am the child process, my process id is 23
0x7ffd3ed42530
统计结果是: 1
0
Finish