fork() 与 vfork()比较

来源:互联网 发布:淘宝卖家购物车怎么看 编辑:程序博客网 时间:2024/06/09 11:21

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







原创粉丝点击