利用fork创建多个子进程,一个程序中的父进程是同一个。
//
// main.cpp
// fork
//
// Created by 蓝猫 on 2018/10/29.
// Copyright © 2018年 蓝猫. All rights reserved.
//
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
int main(int argc, const char * argv[])
{
pid_t pid1,pid2;
cout<<" 多进程测试"<<endl;
pid1=fork();
if(pid1<0)
{
cout<<"error"<<endl;
exit(1);
}
else if (pid1==0)
{
cout<<"子进程1,进程标示符:"<<getpid()<<endl;
}
else//pid是子进程pid
{
sleep(1);// 父进程等一秒钟
cout<<"子进程1的父进程,进程标示符:"<<getpid()<<" 子进程1:"<<pid1<<endl;
pid2=fork();//再创建一个
if(pid2<0)
{
cout<<"error"<<endl;
exit(1);
}
else if(pid2==0)
{
cout<<"子进程2,进程标示符:"<<getpid()<<endl;
}
else
{
cout<<"子进程2的父进程,进程标示符:"<<getpid()<<" 子进程2:"<<pid1<<endl;
}
}
cout<<"多进程测试,即将结束"<<endl;
return 0;
}