linux中fork的使用

linux中fork的使用

fork用于创建进程的内容,在linux中,可以在一个主线程中,创建子线程;
两个进程之间的内容是独立的,互补影响的;

pid_t pid = fork();

该函数会返回两个值,返回子线程的pid,子线程则会返回0;

#include <iostream>
#include <stdio.h>
#include <unistd.h>
using namespace std;
int main()
{
    int i = 0; 
    cout<<"before fork"<<endl;
    pid_t pid = fork();
    cout<<"after fork"<<endl;
    if(pid < 0)
    {
        cout<<"error"<<endl;
        return 1;
    }
    else if(pid == 0)
    {
        cout<<"fork sucess, this is son process"<<endl;
        while(i < 10)
        {
            i += 1;
            cout<<"this is son process, i = "<<i<<endl;
            sleep(1);
        }
    }
    else
    {
        cout<<"fork sucess, this is father process, son process pid="<<pid<<endl;
        while(i < 10)
        {
            i += 2;
            cout<<"this is father process i="<<i<<endl;
            sleep(2);
        }
    }
    cout<<"process destroy"<<endl;
    return 0;
}

最后的输出结果为:

before fork
after fork
fork sucess, this is father process, son process pid=4349
this is father process i=2
after fork
fork sucess, this is son process
this is son process, i = 1
this is son process, i = 2
this is son process, i = 3
this is father process i=4
this is son process, i = 4
this is son process, i = 5
this is father process i=6
this is son process, i = 6
this is son process, i = 7
this is father process i=8
this is son process, i = 8
this is son process, i = 9
this is father process i=10
this is son process, i = 10
process destroy
process destroy
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值