【问题标题】:Why doesn't the child execute after the fork()? It never gets to child's part of code.为什么孩子在 fork() 之后不执行?它永远不会涉及到孩子的代码部分。
【发布时间】:2014-02-10 09:48:29
【问题描述】:

这是我的代码。我基本上想创建一个子进程,它将通过 execvp() 执行一些命令。然而,该程序永远不会到达那里,因为它永远不会打印“Got to child”。我不明白为什么。有人可以解释错误是什么吗?因为我认为我正在遵循 t 的程序。

    pid_t pid;
    pid = fork();

    if (pid < 0) { //if fork() returns less than 1 it failed
        fprintf(stderr, "fork failed");
        return 1;
    }
    else if (pid == 0) {  //for() returns 0 then this is the child process
        printf("Got to child");
        int exec;
        exec = execvp(args[0], args); /* (2) invoke execvp() */
        if (exec < 0) {
            printf("Error: executing command failed.\n");
            exit(1);
        }
    }
    else { //pid>0 therefore this is the parent process
        if (background == 0){
        wait(&status);
        printf("Got to parent");
        }
    }

【问题讨论】:

  • 请发布有效的、可编译的代码。另外,删除与问题无关的代码。更改后,确保它仍然可以编译,并重现问题...
  • 在你的 printf 中换行或刷新它。

标签: c linux fork pid


【解决方案1】:

您看不到Got to child,因为您没有在消息末尾包含换行符。如果添加换行符,您可能会突然看到该消息。如果您想合理确定看到输出,请在消息末尾使用换行符。如果您想更确定这样做,请添加fflush(stdout);fflush(0);

您不需要测试来自execvp() 的返回值。只有在不成功时才会返回。您应该将错误消息报告给标准错误,而不是标准输出。

【讨论】:

  • 其实我总是在forkexecve之前做一个fflush(NULL);
  • @BasileStarynkevitch fflush(NULL),刷新所有打开写入的流……听起来是个好主意。
【解决方案2】:

这看起来像典型的模式,但我想知道是否

printf("Got to child");

没有 \n 会导致未写入的缓冲区在 exec 发生时被丢弃,因此没有输出。

【讨论】:

  • @user3217278 这不是魔术,它被称为“行缓冲”:-)。有关详细信息,请参阅 `setbuf(3)`。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-20
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
  • 2021-07-24
  • 1970-01-01
相关资源
最近更新 更多