c - a simple fork program -


#include <stdio.h> #include <sys/types.h> #include <unistd.h> int main () {   pid_t child_pid;   printf ("the main program process id %d\n", (int) getpid());   child_pid = fork () ;   if (child_pid != 0)    {     printf ("this parent process, id %d\n", (int) getpid ());     printf ("the child's process id %d\n",(int) child_pid );   }   else     printf ("this child process, id %d\n", (int) getpid ());   return 0; } 

i have written simple fork program create process , when run program output follows :

the main program process id 3322 child process , id 0 

now point , why isn't if block getting executed in, in parent process return value of fork() not equal 0 why not getting output if block ?

the following code have @ least 2 problems:

#include <stdio.h> #include <sys/types.h> #include <unistd.h> int main () {     pid_t child_pid;     printf ("the main program process id %d\n", (int) getpid());     child_pid = fork () ;     if (child_pid > 0)      {         printf ("this parent process, id %d\n", (int) getpid ());         printf ("the child's process id %d\n",(int) child_pid );     }     else if (child_pid == 0)         printf ("this child process, id %d\n", (int) getpid ());     else         printf ("fork failed\n");      return 0; } 
  1. it did not flush output buffer after first printf().

    if output of program redirected file, output become block buffered, output of printf() may or may not written output file, therefore, output file 5 or 4 lines (actually, of them 5 lines).

    add fflush(stdout); after first printf() can fix problem.

  2. the parent process terminated before child process.

    in case, once or twice in several thousands of runs of program, output of child process lost, output file has 3 lines. after fflush() added, output file should 4 lines.

    i not understand why happens, or whether correct. fortunately, quite easy fix. add wait(null); after third printf() enough.


here helpful explanation art:

  1. posix mandates file descriptors in child process after fork point same file descriptions (file descriptions not same thing file descriptors). file descriptions contain (among others) file offset. printf go through write write out output , write guaranteed atomically update file offset , write out data. redirecting output in forking program safe long program doesn't seek (which you're not supposed on stdout , printf shouldn't).

  2. references didn't fit in previous comment: file description, fork.


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -