Thursday, 15 July 2010

c - Child process executes statements written before fork call -



c - Child process executes statements written before fork call -

i creating kid process in code. when phone call fork(), kid process should start execution next statement, in code, kid process executes statement before fork call.

#include<stdio.h> int main() { int pid; file *fp; fp = fopen("oh.txt","w"); fprintf(fp,"i before fork\n"); pid = fork(); if(pid == 0) { fprintf(fp,"i within kid block\n"); } else{ fprintf(fp,"i within parent block\n"); } fprintf(fp,"i within mutual block both parent , child\n"); fclose(fp); homecoming 0; }

this output get

output: i before fork within parent block within mutual block both parent , kid before fork within kid block within mutual block both parent , kid

the line "i before fork" should written 1 time in file written twice kid , parent. why so?

thank you.

this buffering issue. fprintf doesn't write file immediately, buffers output. when fork, end 2 copies of buffer.

try doing fflush(fp) before forking , see if solves issue.

c fork ipc

No comments:

Post a Comment