CS360 Final -- December 11, 1999. Question 2

The following code is in prog1.c, which takes one command line argument:
main(int argc, char **argv)
{
  FILE *f1;

  if (argc != 2) { fprintf(stderr, "usage: prog1 file\n"); exit(1); }
  f1 = fopen(argv[1], "w");

  ....   /* Various code that writes to both standard output and f1 */

  fclose(f1);
}
This program has two outputs -- standard output, and the file named as the first command line argument. Suppose instead that you would like the first output (the output that currently goes to standard output) to be the standard input of the program prog2. Additionally, you would like the second output (the output that goes to f1) of the program to be the standard input of the program prog3.

Obviously, you could do this with shell commands:

UNIX> prog1 tmpfile | prog2
UNIX> prog3 < tmpfile
UNIX> rm tmpfile
However, your job is to modify prog1.c so that it achieves the above functionality by calling fork(), execlp(), etc., and works without creating any temporary files (such as tmpfile in the example above).

You may not call system() or popen().

You will want to make use of the standard I/O library call fdopen():

     FILE *fdopen(int fildes, const char *type);
This creates a standard I/O buffer that will read from or write to the file descriptor specified by filedes. If the second argument is "r", the returned buffer can be used for reading (e.g. with fscanf() or fgets()), and if it is "w", then the returned buffer can be used for writing (e.g. with fprintf() or fputs()).

Use the Answer Sheet for Question 2 included at the end of the exam.