C++通过fork创建子进程实战

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/88925229

一 代码

#include <iostream>
using namespace std;

#include <unistd.h>  
#include <stdio.h>   
int main()   
{   
    pid_t fpid;  
    int count = 0;  
    fpid = fork();   //返回子进程的进程ID
    if (fpid < 0)     //如果返回负数,则出错了
        cout<<"failed to fork";   
    else if (fpid == 0)  //如果fork返回0,则下面进入子程序 
    {  
        cout<<"I am the child process, my pid is  "<<getpid()<<endl;   
        count++;  
    }  
    else   //如果fork返回值大于0,则依旧在父进程中执行
    {  
        cout<<"I am the parent process, my pid is "<<getpid()<<endl;
        cout << "fpid =" << fpid << endl;
        count++;  
    }  
    printf("count=%d\n", count);  
    return 0;  
}  

二 运行

[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
I am the parent process, my pid is 995
fpid =996
count=1
[root@localhost test]# I am the child process, my pid is  996
count=1

三 说明

fork函数创建一个子进程。如果成功,在父进程的程序中将返回子进程的进程ID,即PID。子进程在返回0的分支继续运行,父进程在返回子进程号的分支继续运行。如果失败,则在父进程程序中返回-1。

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/88925229