我从APUE获取了代码。在Ubuntu 12.04中,如果我使用gcc而不进行任何优化,我将得到与书中相同的结果:
pid = 4122, glob = 7, var = 89.
如果我使用 gcc -O2,则 var 将为 88。 这是因为 gcc 优化会使用 vfork() 做一些事情吗?
#include "apue.h"
int glob = 6;
int
main(void)
{
int var;
pid_t pid;
var = 88;
printf("before vfork\n");
if ((pid = vfork()) < 0) {
err_sys("vfork error");
} else if ( pid ==0) {
glob++;
var++;
_exit(0);
}
printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var);
exit(0);
}
最佳答案
根据规范,子代码中的这两行
glob++;
var++;
引发未定义的行为。
来自Linux man vfork
:
(From POSIX.1) [...] 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() [...]
可能值得注意的是,vfork()
在 POSIX 的先前版本中“标记为过时”(请参阅上面的 POSIX 链接),并且是 removed from POSIX with Issue 7 (POSIX.1-2008) :
Applications are recommended to use the fork() function instead of this function.
The vfork() function was previously under-specified.
关于c - vfork() 与 gcc -O2 似乎有错误的结果。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20716523/