c - fork() 后没有得到预期的输出。为什么?

标签 c fork fork-join

我有一个可以派生的 C 程序,我从 linux bash shell 运行该程序。

问题:- fork 后未获得预期输出。

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
void main(){
    pid_t p1;
    int size;
    char *new;
    char test[2]={'\0'};
    int arr[5]={1,2,3,4,5};
    printf("\nIn Parent process");
    printf("\nElements of Array are:");
    for(int i=0;i<5;i++) { 
         printf("%d ",arr[i]);
    }
    p1=fork();
    if(!p1) {
        printf("\nIn child Process");
    }
    wait(NULL);
}

实际结果

In Parent process
Elements of Array are:12345
In child ProcessElements of Array are:12345

期望的输出:-

In Parent process
Elements of Array are:12345
In child Process

最佳答案

我在 this related Q/A 中找到了您的问题。基本上,printf() 方法的输出正在被缓冲,并且该缓冲区正在被子进程使用。如果您在 fork 之前调用 fflush(0),您的 IO 缓冲区应该会正确刷新,并且您应该获得所需的输出。希望有帮助。

关于c - fork() 后没有得到预期的输出。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57237820/

相关文章:

javascript - Angular - 使用 mergeMap 从 2 个 API 获取数据并将它们保存在数组中

java - 使用 fork/join 架构扩展时出现 StackOverflowError

c - 将数据输入数组的函数,在 EOF 处退出输入但允许恢复输入

c - 使用 fork() 时收割子进程

c - Unix 进程 fork 层次结构

Python Popen.waitpid 返回 "[Errno 10] No child processes"

java - fork /加入 JavaEE 应用程序?

c++ - 混合 C 和 C++ 的线程同步

c - 统计信息未显示正确的 inode 号

c++ - 静态库如何链接到依赖项?