You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言使用fork创建进程时无法生成孙进程的原因是什么?

你的代码存在三个核心问题,导致运行结果不符合预期:

  • wait(NULL)的调用位置错误。你把它放在了第一次fork()之后、switch分支之前,fork()返回后父子进程都会执行后续代码,子进程还没创建孙进程就会先执行wait(NULL),此时子进程没有任何子进程,wait调用无意义;同时父进程会提前等待子进程执行完成才走自己的分支,逻辑混乱。
  • 没有对第二次fork()的返回值做判断。printf("Grandchild ID? %d\n", getpid())会被首次创建的子进程、以及子进程fork出来的孙进程各执行一次,你无法区分打印的ID属于哪个进程。
  • 子进程创建孙进程后没有做资源回收,孙进程可能变为孤儿进程,ID显示异常。

修正后的可运行代码如下:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(void) {
  pid_t pid = fork();
  
  switch(pid)
  {
    case -1:
      perror("fork failed");
      break;
    case 0:
      printf("子进程ID:%d,父进程ID:%d\n", getpid(), getppid());
      pid_t pid2 = fork();
      switch(pid2) {
        case -1:
          perror("fork grandchild failed");
          break;
        case 0:
          printf("孙进程ID:%d,父进程ID:%d\n", getpid(), getppid());
          break;
        default:
          wait(NULL);
          break;
      }
      break;
    default:
      printf("父进程ID:%d\n", getpid());
      wait(NULL);
      break;
  }
  return 0;
}

运行后可清晰看到三层进程的ID关联关系:孙进程的父ID等于子进程ID,子进程的父ID等于根父进程ID,符合预期。

内容的提问来源于stack exchange,提问作者ballstowall

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 22:39:03