vfork()函数的使用

vfork()函数的使用

前言:

vfork()函数与fork()函数创建进程的区别:
区别一:
vfork()创建的子进程直接使用父进程的存储空间,不进行拷贝。、
区别而:
vfork()创建的子进程,是子进程先运行,当子进程调用exit(0)退出,父进程才执行。

代码如下:

  1 #include <sys/types.h>
  2 #include <unistd.h>
  3 #include<stdio.h>
  4 #include<stdlib.h>
  5 
  6 int main()
  7 {
  8     pid_t pid;
  9     int i=0;
 10     pid=vfork();//调用vfork()函数
 11     if(pid==0)
 12       {
 13         while(1)
 14           {
 15              //打印子进程进程号信息。
 16              printf("The child  process is running ! pid=%d \n",getpid());
 17              sleep(2);
 18              i++;
 19              if(i==3)
 20               {
 21                  //当子进程运行3 次就退出
 22                   printf("The child process will be exit !\n");
 23                   exit(0);
 24               }
 25           }
 26       }else if(pid>0)
 27           {
 28         while(1)
 29                 {
 30                  //打印夫进程进程号信息。
 31                  printf("The parent process is running ! pid=%d \n",getpid());
 32                  sleep(2);
 33                 }
 34           }
 35     return 0;
 36 }

运行结果:

@Embed_Learn:~$ ./a.out
The child  process is running ! pid=4423 
The child  process is running ! pid=4423 
The child  process is running ! pid=4423 
The child process will be exit !
The parent process is running ! pid=4422 
The parent process is running ! pid=4422 
The parent process is running ! pid=4422 
The parent process is running ! pid=4422 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值