为什么将 pid 保留在 char 中,始终为 0?

Nit*_*dam 1 c fork

#include <stdio.h>
#include <string.h>
#include <unistd.h>

struct mystruct {
  char string[3];
  char pid
};

int main(int argc, char** argv) {
  struct mystruct info;
  info.pid = fork();
  strcpy(info.string, "Son");
  if (info.pid == 0)
    printf("%s", info.string);
  else
    printf("Father");
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

此代码打印

Son
Son
Run Code Online (Sandbox Code Playgroud)

我想知道为什么。

Nat*_*dge 8

"Son"由于终止空字节,该字符串需要 4 个字节。但是info.string只有 3 个字节的空间,所以你会溢出它,导致未定义的行为。很可能空字节被info.pid0覆盖,因为这可能是内存中的下一个字节。

无论如何,不​​要尝试将结果存储fork()char. 它返回 a pid_t,这是您应该使用的类型。很可能会溢出一个char. 如果返回的 pid 恰好是 256 的倍数,您的代码会错误地认为两个进程都是子进程。