/* file: simple_fork1.c See comments and questions at the end of this file. Compare against simple_fork0.c and simple-fork1.cc. */ #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)) { /* use of gets() is very bad programming here -- Why? ==================== */ fprintf (stderr, "you must provide a filename\n"); exit (-1); } } else strcpy (pathname, argv[1]); /* use of strcpy() is very bad programming here -- Why? ==================== */ 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 ()); fork (); i++; } fclose (ofstream); close (outfildes); return 0; } /* Purpose: Extend the simple_fork0.c to illustrate the effects of fork() on bufffered output. Illustrate how one opens a named file and associates it with a stream in C, versus C++. To compile this program: gcc -o simple_fork1 simple_fork1.c To run this program: ./simple_fork1 abc Sample terminal output, when the above was done on a Linux machine with two CPU's: [cop4610@websrv forkexec]$ ./simple_fork1 abc i = 0 in 27398 i = 1 in 27398 i = 1 in 27399 i = 2 in 27398 i = 2 in 27399 i = 2 in 27400 [cop4610@websrv forkexec]$ i = 2 in 27401 Why is there output after the second prompt? Sample output on file "abc", for same run: i = 0 in 27561 i = 1 in 27562 i = 2 in 27562 i = 0 in 27561 i = 1 in 27562 i = 2 in 27564 i = 0 in 27561 i = 1 in 27562 i = 2 in 27564 i = 0 in 27561 i = 1 in 27562 i = 2 in 27562 i = 0 in 27561 i = 1 in 27561 i = 2 in 27563 i = 0 in 27561 i = 1 in 27561 i = 2 in 27563 i = 0 in 27561 i = 1 in 27561 i = 2 in 27561 i = 0 in 27561 i = 1 in 27561 i = 2 in 27561 Why are there more lines of output written to the file "abc" than to the terminal? Why does the C++ version (simple-fork0.cc) not have these extra lines? If there is any detail of this program that you cannot figure out, ask questions, either in class, on the course discussion board, or by e-mail to one of the instructors for this course. */