学习分享:fork函数与vfork函数的区别

一、fork函数

(一)fork函数头文件

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

(二)fork函数原型

         pid_t fork(void);

(三)fork函数的作用

通过复制正在调用的进程来创建一个新的进程,这个新的进程被称为子进程。

(四)返回值

父进程:返回子进程id

子进程:返回0

错误:返回-1

(五)用法展示

#include <strings.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[])
{ 

    pid_t pid = fork();//创建子进程
    if(pid == -1)
    {
        perror("fork");
        return -1;
    }                  //判断是否创建成功
    if(pid == 0)       //返回0则为子进程
    {
        printf("the child id is:%d,the parent id is:%d\n",getpid(),getppid());
    }
    else              //否则为父进程
    {
        printf("the parent id is:%d,my parent id is:%d",getpid(),getppid());
    }
    return 0;
} 

二、vfork函数

(一)vfork函数头文件

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

(二)vfork函数原型

         pid_t vfork(void);

(三)vfork函数的作用

vfork函数拥有跟fork函数一样用于创建子进程的作用,但是vfork并不拷贝父进程的叶表

(四)返回值

父进程:返回子进程id

子进程:返回0

错误:返回-1

(五)用法展示

#include <strings.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[])
{ 

    pid_t pid = vfork();//创建子进程
    if(pid == -1)
    {
        perror("vfork");
        return -1;
    }                  //判断是否创建成功
#include <strings.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[])
{ 

    pid_t pid = fork();//创建子进程
    if(pid == -1)
    {
        perror("fork");
        return -1;
    }                  //判断是否创建成功
    if(pid == 0)       //返回0则为子进程
    {
        printf("the child id is:%d,the parent id is:%d\n",getpid(),getppid());
    }
    else              //否则为父进程
    {
        printf("the parent id is:%d,my parent id is:%d",getpid(),getppid());
    }
    return 0;
} 
    return 0;
} 

(三)区别

vfork不将父进程中的地址空间完全复制到子进程,仅与父进程共享数据段,fork函数父子进程的运行次序是不确定的,而vfork函数保证了子进程先运行,在调用exec 或exit 之前与父进程数据是共享的,在它调用exec或exit 之后父进程才可能被调度运行。如果在调用这两个函数之前子进程依赖于父进程的进一步动作,则会导致死锁。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值