A504c 发表于 2012-10-12 10:18

实在不明白这段代码为什么会发生segmentation fault。

int a=20;
if(vfork()==0)
{a=30;
cout<<"c:"<<a<<endl;
}else{
cout<<"f:"<<a<<endl;
}

A504c 发表于 2012-10-12 10:27

谁能帮忙解答一个啊!!!!
谢谢啊

MMMIX 发表于 2012-10-12 11:58

A504c 发表于 2012-10-12 10:27 static/image/common/back.gif
谁能帮忙解答一个啊!!!!
谢谢啊

man 2 vfork

观夜天象 发表于 2012-10-12 12:43

vfork() differs from fork(2) in that the parent is suspended untilthe
       childterminates (either normally, by calling _exit(2), or abnormally,
       after delivery of a fatal signal), or it makesacalltoexecve(2).
       Untilthat point, the child shares all memory with its parent, includ‐
       ing the stack.The child must not return from the current functionor
       call exit(3), but may call _exit(2).第四行下加_exit(0);

A504c 发表于 2012-10-12 12:56

谢谢提醒,看了一下大概懂了。不过有一句不是特别明白:It does not work, however, to return while running in the child's context from the procedure that called vfork() since the eventual return from vfork() would then return a no longer existent stack frame.大概就是子进程返回后把父进程的栈注销了,对吧?

MMMIX 发表于 2012-10-12 13:26

本帖最后由 MMMIX 于 2012-10-12 13:27 编辑

观夜天象 发表于 2012-10-12 12:43 static/image/common/back.gif
第四行下加_exit(0);

他那个代码的问题是 vfrok() 后的 a=30; 导致程序会出现未定义行为。

观夜天象 发表于 2012-10-12 14:06

MMMIX 发表于 2012-10-12 13:26 static/image/common/back.gif
他那个代码的问题是 vfrok() 后的 a=30; 导致程序会出现未定义行为。
老大,是写时拷贝,好像不是未定义行为吧。

观夜天象 发表于 2012-10-12 14:10

A504c 发表于 2012-10-12 12:56 static/image/common/back.gif
谢谢提醒,看了一下大概懂了。不过有一句不是特别明白:It does not work, however, to return while runni ...
这里是子进程的栈帧已不存在。

使用vfork(),父子进程的执行次序固定,子进程先执行,父进程会等待其完成,一般紧接着就是调用exec系列函数。

MMMIX 发表于 2012-10-12 16:16

观夜天象 发表于 2012-10-12 14:06 static/image/common/back.gif
老大,是写时拷贝,好像不是未定义行为吧。


   Standard Description
       (FromPOSIX.1) The vfork() function has the same effect as fork(2), except that the behavior 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 callsanyotherfunctionbeforesuccessfully
       calling _exit(2) or one of the exec(3) family of functions.

观夜天象 发表于 2012-10-12 16:44

MMMIX 发表于 2012-10-12 16:16 static/image/common/back.gif

疏忽了,向斑竹学习。
页: [1] 2
查看完整版本: 实在不明白这段代码为什么会发生segmentation fault。