fork() 与 vfork()比较

1.fork() 和vfork()都是创建一个新的进程.但是存在区别: fork()新创建出来的子进程和父进程对调度器而言是平等的,不能知道哪个进程先执行,由调度器决定. 而vfork()创建的子进程一定比父进程先执行. 实例如下:


test.c 

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
    pid_t pid = 0;
    pid = fork();
    if(pid < 0)
    {
        printf("fork error \n");
        exit(1);
    }
    else if(pid == 0)
    {
        printf("Child process \n");
        exit(0);
    }

    printf("Parent process \n");

    return 0;
}

运行结果:

./test

Parent process
Child process


我的调度器优先调用了父进程执行.


test1.c


#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
    pid_t pid = 0;
    pid = fork();
    if(pid < 0)
    {
        printf("fork error \n");
        exit(1);
    }
    else if(pid == 0)
    {
        printf("Child process \n");
        exit(0);
    }
    
    sleep(3);

    printf("Parent process \n");

    return 0;
}

让父进程先休眠3秒,子进程优先被调度.


运行结果:


./test1

Child process
Parent process


test2.c


#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
    pid_t pid = 0;
    pid = vfork();
    if(pid < 0)
    {
        printf("fork error \n");
        exit(1);
    }
    else if(pid == 0)
    {
        printf("Child process \n");
        exit(0);
    }

    printf("Parent process \n");

    return 0;
}

使用vfork() 后,不用父进程休眠,子进程也会被优先调度.


运行结果:

./test2

Child process
Parent process







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值