/* file: simple_fork2.c The addition of fflush() to simple_fork1.c eliminates problem of child inheriting uflushed output buffers from parent. */ #define _XOPEN_SOURCE 500 #include #include #include #include #include #include int main(int argc, char *argv[]) { char pathname [32]; int i = 0; int outfildes; FILE *ofstream; if (argc < 2) { fprintf (stdout, "Please enter a filename or pathname: "); if (!gets (pathname)) { fprintf (stderr, "you must provide a filename\n"); exit (-1); } } else strcpy (pathname, argv[1]); if ((outfildes = open (pathname, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR)) == -1) { fprintf (stderr, "could not open file \"%s\" for writing: %s\n", pathname, strerror (errno)); exit (-2); } if (!(ofstream = fdopen (outfildes, "w"))) { perror ("could not open stream for writing"); exit (-3); } while (i < 3) { fprintf (stdout, "i = %d in %d\n", i, getpid ()); fprintf (ofstream, "i = %d in %d\n", i, getpid ()); fflush (stdout); fork (); i++; } fclose (ofstream); close (outfildes); return 0; }