//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
本文通过两个示例程序对比了fork()与vfork()系统调用的行为差异。具体展示了父进程与子进程在变量共享及执行顺序上的不同表现。
1364

被折叠的 条评论
为什么被折叠?



