fork与vfork

  1. fork运行后子进程拷贝一份父进程的数据,父进程和子进程不知道谁先运行,完全看系统的调度
  2. vfork直接运用父进程存储空间,不拷贝,vfork保证子进程先运行,运行结束后(exit后)父进程再运行。

先看看fork的程序运行

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

int main()
{
    
    
        pid_t pid;

//      printf("Father pid is%d\n",getpid());
        int data=10;

        pid=fork();
        if(pid>0)
        {
    
    
        while(1)
        {
    
    
                printf("This is father!,pid=%d\n",getpid());
                sleep(1);
        }
        }
        else if(pid==0)
        {
    
    
        while(1){
    
    

                printf("This is child!,pid=%d\n",getpid());
                sleep(1);
        }
        }

//      printf("%d\n",data);
        return 0;
}
~ 

在这里插入图片描述
运行是没有顺序的,完全看系统调度。

下面把fork换成vfork看看结果

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

int main()
{
    
    
        pid_t pid;

//      printf("Father pid is%d\n",getpid());
        int data=10;

        pid=vfork();
        if(pid>0)
        {
    
    
        while(1)
        {
    
    
                printf("This is father!,pid=%d\n",getpid());
                sleep(1);
        }
        }
        else if(pid==0)
        {
    
    
        while(1){
    
    

                printf("This is child!,pid=%d\n",getpid());
                sleep(1);
        }
        }

//      printf("%d\n",data);
        return 0;
}
~   

在这里插入图片描述
会一直执行子的运行

然后我们限制条件让子进程运行一段时间后退出

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

int main()
{
    
    
        pid_t pid;

//      printf("Father pid is%d\n",getpid());
        int data=10;
        int cnt=0;
        pid=vfork();
        if(pid>0)
        {
    
    
        while(1)
        {
    
    
                printf("This is father!,pid=%d\n",getpid());
                sleep(1);
        }
        }
        else if(pid==0)
        {
    
    
        while(1){
    
    

                printf("This is child!,pid=%d\n",getpid());
                sleep(1);
                cnt++;
                if(cnt==3)
                {
    
    
                        exit(0);
                }
        }
        }

//      printf("%d\n",data);
        return 0;
}

看结果

在这里插入图片描述
子进程运行三次后开始父进程的运行

猜你喜欢

转载自blog.csdn.net/qq_43482790/article/details/115186207