simple fork() problem

I have this little program ...

int main(void){
  
    printf("Before");
    fork();
    printf("After");

}

output is this.....

BeforeAfterBeforeAfter

Shouldnt it be.....BeforeAfterAfter

After parent is forked child receives the copy of program and continues from next statement which is "after". Parent as well after fork continues to next statement which is "after"...

Anyone have any suggestions please

use write() instead of printf(). printf() is buffered, and the child has a copy of the buffer so it also will bring "before" and then print after.

changing the first printf to

 write(1,"Before", 7); 

and the second to

 write(1,"After",5);

will give you the behavior you want.

Yes, FILE* s all buffered inside a process, not in the O/S, so you must flush().

or simpler, properly terminate your lines:

int main(void)
{
    printf("Before\n");
    fork();
    printf("After\n");
}