【问题标题】:Why keeps pid in char giving always 0?为什么将 pid 保留在 char 中始终为 0?
【发布时间】:2021-07-03 06:09:06
【问题描述】:
#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

我想知道为什么。

【问题讨论】:

  • 如果您正在做一些奇怪的事情(将某个较大类型的值分配给 char),开始调试的一个好地方是发现奇怪的事情是否是意外行为的原因。打印出 pid(作为 pid_t)及其截断时的值是我首先尝试的。

标签: c fork


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    这应该可以如你所愿,看看变化 insisde 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2014-01-09
      • 1970-01-01
      相关资源
      最近更新 更多