#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main(void)
{
pid_t pid=fork();
if(pid<0){
perror("fork creat ");
}else if(pid>0){//父进程
printf("this is parent process\n");
}else{//pid=0//子进程
printf("this is child process\n");
}
sleep(1);
return 0;
}
运行结果:子父进程是随机运行的
xfliu@ubuntu:创建进程$ ./bin/1
this is child process
this is parent process
xfliu@ubuntu:创建进程$ ./bin/1
this is parent process
this is child process
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main(void)
{
pid_t pid=fork();
int i=0;
printf("the start value of i is %d\n",i);
if(pid<0){
perror("fork creat ");
}else if(pid>0){//父进程
++i;
printf("this is parent process\n");
printf("i=%d\n",i);
}else{//pid=0//子进程
--i;
printf("this is child process\n");
printf("i=%d\n",i);
}
sleep(1);
return 0;
}
运行结果:证明两进程资源是独立的
the start value of i is 0
this is parent process
i=1
the start value of i is 0
this is child process
i=-1
接下来是使用vfork函数:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdlib.h>
int i=0;
int main(void)
{
pid_t pid=vfork();
printf("the start value of i is %d\n",i);
if(pid<0){
perror("vfork creat ");
}else if(pid>0){//父进程
++i;
printf("this is parent process\n");
printf("i=%d\n",i);
}else{//pid=0//子进程
--i;
printf("this is child process\n");
printf("i=%d\n",i);
}
//sleep(1);
exit(0);//不能是return函数详见使用vfork过程中出现段错误 - feiyangyangfei的专栏 - 博客频道 - CSDN.NET
http://blog.csdn.net/feiyangyangfei/article/details/12577661 版权归该链接博主所有
}
运行结果:父子进程没有公用,且子进程先运行
the start value of i is 0
this is child process
i=-1
the start value of i is 0
this is parent process
i=0