一、fork vs vfork
1、使用vfork时,父、子进程中不能同时使用return,否则会报--Segmentation fault。--why???(暂时还没整明白!)
2、使用vfork时,确保子进程先执行--父、子进程共享地址空间,父进程阻塞,等子进程退出后,父进程才继续执行
如果子进程没有执行exec或者exit,这时在进程中请求父进程中的资源,会导致死锁!(父进程等子进程退出,子进程等父进程的资源)
3、fork,子进程复制父进程的所有资源(包括进程环境、内存资源)--但子进程有自己的数据段--父、子进程中修改自己变量的值,
不会影响到对方;
vfork,子进程不复制父进程资源,父、子进程共享地址空间,修改虚拟内存空间中变量的值,会影响到对方
二、示例
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <unistd.h>
-
-
typedef unsigned int UINT32;
-
UINT32 g_tmp = 10;
-
-
int main()
-
{
-
pid_t pid;
-
UINT32 tmp = 5;
-
pid = fork();
-
if(pid<0)
-
{
-
printf("fork error!\n");
-
exit(1);
-
}
-
else if(0==pid)
-
{
-
printf("child process:pid=%d\n",getpid());
-
g_tmp++;
-
tmp++;
-
printf("g_tmp=%d\n tmp= %d\n",g_tmp,tmp);
-
}
-
else
-
{
-
printf("parent process:pid=%d\n",getpid());
-
g_tmp++;
-
tmp++;
-
printf("g_tmp=%d\n tmp= %d\n",g_tmp,tmp);
-
}
-
-
return 0;
-
}
-
-
/*运行结果*
-
child process:pid=3963
-
g_tmp=11
-
tmp= 6
-
parent process:pid=3962
-
g_tmp=11
-
tmp= 6
-
*/
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <unistd.h>
-
-
typedef unsigned int UINT32;
-
UINT32 g_tmp = 10;
-
-
int main()
-
{
-
-
pid_t pid;
-
UINT32 tmp = 5;
-
pid = vfork();
-
if(pid<0)
-
{
-
printf("fork error!\n");
-
exit(1);
-
}
-
else if(0==pid)
-
{
-
printf("child process:pid=%d\n",getpid());
-
g_tmp++;
-
tmp++;
-
printf("g_tmp=%d\n tmp= %d\n",g_tmp,tmp);
-
//exit(0);
-
return 0;
-
}
-
else
-
{
-
printf("parent process:pid=%d\n",getpid());
-
g_tmp++;
-
tmp++;
-
printf("g_tmp=%d\n tmp= %d\n",g_tmp,tmp);
-
exit(0);
-
//return 0;
-
}
-
}
-
-
/*
-
运行结果
-
child process:pid=6156
-
g_tmp=11
-
tmp= 6
-
parent process:pid=6155
-
g_tmp=12
-
tmp= 1
-
*/
阅读(595) | 评论(0) | 转发(0) |