Linux系统编程——进程(三)fork函数和vfork函数的区别

142 阅读1分钟

1、vfork函数直接使用父进程的存储空间,不拷贝
2、vfork保证子进程先运行,当子进程调用exit退出后,父进程才执行

用fork函数创建进程

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int data = 3;
    pid_t pid;
    pid = fork();
    if(pid > 0){
        while(1){
             printf("Father pid = %d\n",getpid());
             sleep(1);
        }
     }else if(pid == 0){
     	while(1){
        	data--;      //将child打印3次
            printf("Child pid = %d\n",getpid());
            sleep(3);
            if(data == 0){
            	exit(0);
            }
        }
    }
    return 0;
}

在这里插入图片描述
可以看到用fork函数创建进程时,父进程和子进程都在运行

当用vfork函数创建函数时

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int data = 3;
    pid_t pid;
    pid = vfork();
    if(pid > 0){
        while(1){
             printf("Father pid = %d\n",getpid());
             sleep(1);
        }
     }else if(pid == 0){
     	while(1){
        	data--;      //将child打印3次
            printf("Child pid = %d\n",getpid());
            sleep(3);
            if(data == 0){
            	exit(0);
            }
        }
    }
    return 0;
}

在这里插入图片描述
可以看到用vfork创建子进程时,子进程先运行,当子进程调用exit退出后,父进程才执行

再看下面代码

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
    pid_t pid;
    int data = 100;
    int i = 5;
    pid = vfork();
    if(pid > 0){
        while(i != 0){
            printf("this is father pid : %d\n",getpid());
            printf("father data = %d\n",data);
            i--;
        }
    }
    else if(pid == 0){
        printf("this is child pid : %d\n",getpid());
        data++;
        printf("child data = %d\n",data);
        exit(0);
    }
    return 0;
}

在这里插入图片描述
在子进程中修改了data的值,在父进程里面打印的是子进程里面修改的值,所以vfork函数创建进程是直接使用父进程的存储空间,并不是拷贝,而用fork函数创建进程是把内容拷贝给子进程

下面是用fork创建的子进程

pid = vfork();

在这里插入图片描述