Child process executes statements written before fork call

c, fork, ipc

Solution

This is probably a buffering issue. `fprintf` doesn't write to the file immediately, but buffers the output. When you `fork`, you end up with two copies of the buffer.

Try doing an `fflush(fp)` before forking and see if that solves the issue.

Problem

I am creating the child process in my code. When i call the fork(), child process should start its execution from next statement, but in my code, child process executes the statement before the fork call. ``` #include<stdio.h> int main() { int pid; FILE *fp; fp = fopen("oh.txt","w"); fprintf(fp,"i am before fork\n"); pid = fork(); if(pid == 0) { fprintf(fp,"i am inside child block\n"); } else{ fprintf(fp,"i inside parent block\n"); } fprintf(fp,"i am inside the common block to both parent and child\n"); fclose(fp); return 0; } ``` This is the output which i get OUTPUT: ``` i am before fork i inside parent block i am inside the common block to both parent and child i am before fork i am inside child block i am inside the common block to both parent and child ``` The line "i am before fork" should be written once in the file but it is written twice by child and parent. Why it is so? Thank you.

Original source