我有一个可以派生的 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/