fork()与vfork()的区别

来源:互联网 发布:七天网络 编辑:程序博客网 时间:2024/05/16 18:07

//fork():

#include<unistd.h>
#include<stdio.h>
void main(){
   pid_t pid;
   int i=0;
   //pid=vfork();
   pid=fork();
   if(pid<0)
     printf("error");
   else if(pid==0){
      i++;
     printf("i am the child process,id is %d my father is%d\n",getpid(),getppid());
     printf("child say:i is %d\n",i);
     exit(0);
    }
   else{
     i++;
     printf("i am the parent process,id is %d\n",getpid());
     printf("parent say:i is %d\n",i);}
}

运行结果:

i am the parent process,id is 3247
parent say:i is 1
i am the child process,id is 3248 my father is3247
child say:i is 1


//vfork():

#include<unistd.h>
#include<stdio.h>
void main(){
   pid_t pid,pit;
   int i=0;
   pid=vfork();
   //pid=fork();
   if(pid<0)
     printf("error");
   else if(pid==0){
      i++;
     printf("i am the child process,id is %d my father is%d\n",getpid(),getppid());
     printf("child say:i is %d\n",i);
     exit(0);
    }
   else{
     i++;
     printf("i am the parent process,id is %d\n",getpid());
     printf("parent say:i is %d\n",i);}
}

运行结果:

i am the child process,id is 3337 my father is3336
child say:i is 1
i am the parent process,id is 3336
parent say:i is 2