fork函数 创建多进程

原文链接:fork函数 创建多进程

fork多进程:<unistd.h>

<unistd.h>

linux在<unistd.h>提供了许多系统调用函数,包括提供了fork函数创建父子进程,实现多进程.以及其他必要的函数.

//<unistd.h>:
fork():创建一个子进程的副本。
exec*():用于在当前进程上执行一个新的程序。exec是一个函数集,有多个函数
wait():等待子进程结束。
getpid():获取当前进程的进程ID。
getppid():获取当前进程的父进程ID。
chdir():改变当前工作目录。
gethostname():获取主机名。
sysconf():获取系统配置信息。
fork函数

fork后子进程会完全复制父进程的数据,包括文件描述符列表,因此能够支持后面的管道通信.

pid_t fork()
return -1(失败) 0(子进程返回值) >0(父进程中返回子进程的pid)

调用fork()时, 会生成一个当前程序副本,由另一个子进程执行,父子进程都从fork()处继续执行

但是 fork() 能够返回不同的值:
父进程的fork返回id>0,是子进程的pid,
子进程的fork返回0, 子进程可以getpid()和getppid()获取父子的pid.
当出错时返回-1 :此时子进程不会被创建.

实例:fork和exec实现创建多个子进程

parent.cpp

#include <iostream>
#include <unistd.h>
#include <sys/wait>
#include <filesystem>
#include <vector>
using namespace std;

int child_process(const char* program_name,char** args){
    pid_t cpid=fork();
    if(cpid==-1){
        perror("fork");
        exit(EXIT_FAILURE);
    }else if(cpid>0){
        return cpid;
    }else{
        execve(program_name,args,nullptr);
        perror("execve");
        exit(EXIT_FAILURE);
    }
    
}

int main()
{
    char program_name[]="child.cpp";
    char* args[]={program_name,nullptr};
    
    vector<pid_t> childs(3);
    
    if(!exists(program_name)){
        perror("exists");
        exit(EXIT_FAILURE);
    }
    for(int i=0;i<3;i++){
        childs[i]=child_process(program_name,args);
    }
    
    pid_t cpid;
    while((cpid=wait())>0){
        cout<<"child."<<cpid<<"terminated\n";
    }
    
    return 0;
}

child.cpp

#include <iostream>
#include <unistd.h>
using namespace std;

int main(){
    for(int i=0;i<5;i++){
        cout<<"child."<<getpid()<<"run"<<i<<"\n";
        sleep(1);
    }
    exit(EXIT_SUCCESS);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

aidroid

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值