c - vfork() 与 gcc -O2 似乎有错误的结果。

标签 c linux gcc vfork

我从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/

相关文章:

c - 跟踪 io 系统调用时间的工具

c - 运行 c 程序 - stdio.h 我从哪里得到它?

linux - 带有 libssh2 的 libcurl - 一个或多个链接时可用的库在运行时不可用

c - 为什么 C 编译器不捕获此错误?

c - 如何在 C 中将 struct 作为参数传递并对其进行 memcpy ?

c++ - localhost 套接字是否需要任何类型的 keepalive?

c - 如何检查路径是否通向 c 中的目录之外?

C++11 Geany 设置

c++ - 在 GCC 和 MSVC 中使用 TR1 库

c++ - 海湾合作委员会 4.1.2 : error: integer constant is too large for ‘long’ type