ChinaUnix.net
 >> ChinaUnix.net > C/C++

一个关于进程的问题

作者:xumx     发表时间:2002/11/05 04:15pm

#include <unistd.h>
#include <sys/types.h>
int main(void)
{
int var= 1;
pid_t pid;
printf("before vfork\n");
if((pid=vfork())<0)
{
perror("fork");
exit(1);
}
else if (pid==0)
{
printf("child\n");
var++;
exit(0);
}

printf("var = %d \n",var);
exit(0);
}
运行结果是
before vfork
child
var = 2
为什么是这样的,子进程处调用了exit(0),不是就返回到shell了吗?
应该不会输出var=2。


此文章相关评论:
该文章有5个相关评论如下:(点这儿可以发表评论)
jacamar 发表于: 2002/11/05 11:32pm
fork后就是两个进程了,就像没有关系一样
 
zhutr 发表于: 2002/11/05 11:34pm
只是子进程退出,
父进程并没有退出呀!
当然要打出来了!
 
beggar 发表于: 2002/11/05 11:49pm
vfork和fork不同
vfork在调用exec或exit之前在父进程空间中运行且保证子进程先运行,如果子进程不调用exec或exit父进程永远得不到运行.你用vfork的子进程更改了父进程空间中的的var值,所以你会看到var值为2而不是你想要的1.用fork就能看到你想要的1
 
JohnBull 发表于: 2002/11/06 12:12pm
同意.

(From  XPG4  / SUSv2 / POSIX draft.)  The vfork() function has the same effect as fork(), except that  the  behaviour is undefined if the process created by vfork() either modifies any data other than a variable of type pid_t used to store  the  return value from vfork(), or returns from the
function in which vfork() was called, or calls  any  other function before successfully calling _exit() or one of the exec family of functions.

 
aiya 发表于: 2002/11/06 03:13pm
有道理!
 
 

Copyright © ChinaUnix.net  *  转载请注明出处及作者