2

I have a C program that forks, which I'm running from a linux bash shell.

Problem:-After forking Not geetting expected output.

#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);
}

actual result

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

desired output:-

In Parent process
Elements of Array are:12345
In child Process
Christian Hujer
  • 17,035
  • 5
  • 40
  • 47
  • Make sure you end your printing operations with a newline, rather than (or as well as) starting them with a newline. That helps unless you're sending output to a pipe or file instead of a terminal. If you're worried about that, then make sure you use `fflush()` liberally (but note that it slows things down — not too liberally). – Jonathan Leffler Jul 28 '19 at 05:48

1 Answers1

2

I found your problem in this related Q/A. Basically, your output from the printf() method is getting buffered and that buffer is being used by the child process. If you call fflush(0) before you fork, your IO buffer should get flushed properly and you should get the desired output. Hope that helps.

entpnerd
  • 10,049
  • 8
  • 47
  • 68