【问题标题】:fork() causing non-deterministic behavior: child process doesn't executefork() 导致不确定的行为:子进程不执行
【发布时间】:2020-11-24 17:40:02
【问题描述】:

我有一个非常简单的c 程序:

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

int main(int argc, char *argv[] ){
    int rc = fork();

    if (rc < 0){
        // fork failed
        fprintf(stderr, "fork failed\n");
    } else if (rc == 0) {
        printf("hi, I'm child! %d\n", (int) getpid());
        fflush(stdout);
    } else {
        printf("hi, I'm the parent of %d\n", rc);
        fflush(stdout);
    }
    return 0;
}

由于某种原因,当我编译和运行这个程序时,有时会显示两个打印语句,但有时只会显示父进程。

这是为什么?即使我不使用wait(),这两个进程仍应运行。

使用 gcc 7.5.0 ubuntu 18.04

【问题讨论】:

  • 我认为您的代码没有任何问题。你是如何运行程序的?
  • 如果这有什么不同的话,我正在使用 Clion IDE。
  • 应该没什么区别。你是如何运行代码的?通过IDE?尝试在终端内运行它,看看是否有任何变化。您正在运行一个过时的程序或遇到一些非常奇怪的编译器问题。

标签: c unix gcc


【解决方案1】:

因为 IDE 在父进程关闭时停止侦听,或者 shell 将子进程留在后台。

查看任意 printf 顺序:

        int status;
        printf("hi, I'm the parent of %d\n", rc);
        fflush(stdout);
        waitpid(pid, &status, 0);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 2014-06-17
    • 2012-12-16
    • 1970-01-01
    • 2019-02-22
    • 2017-06-27
    • 2020-02-02
    相关资源
    最近更新 更多