fork()與vfork()的區別

//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





發佈了18 篇原創文章 · 獲贊 12 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章