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

问题描述

#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;
}

代码打印

Son
Son

我想知道为什么。

解决方法

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

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

,

这应该如你所愿,看看里面的改动struct mystruct

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

struct mystruct {
  char string[4]; //<- Need 4 instead of 3 because of the terminating null byte
  pid_t pid;      //<- fork() return pid_t
};

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