CS360 Final Exam: December 12, 2000. Question 5: Answer and Grading

This is a simple matter of getting the pipe/dup2/close/wait calls correct. Here is the answer. You could do other things, like making both pipe() calls initially, or closing everything in the parent just before the wait() calls, but this is pretty much it:
#include < stdio.h >
#include < fcntl.h >

main()
{
  int pa[2];
  int pb[2];
  int fd;
  int dummy;

  pipe(pa);

  if (fork() == 0) {

    fd = open("f1", O_RDONLY);
    if (fd < 0) { perror("f1"); exit(1); }

    dup2(fd, 0);
    dup2(pa[1], 1);

    close(fd);
    close(pa[0]);
    close(pa[1]);

    execlp("sort", "sort", NULL);
    perror("execlp");
    exit(1);

  } 

  close(pa[1]);
  pipe(pb);

  if (fork() == 0) {

    dup2(pa[0], 0);
    dup2(pb[1], 1);

    close(pa[0]);
    close(pb[0]);
    close(pb[1]);

    execlp("head", "head", "-5", NULL);
    perror("execlp");
    exit(1);

  }

  close(pa[0]);
  close(pb[1]);

  if (fork() == 0) {

    dup2(pb[0], 0);

    close(pb[0]);

    execlp("cat", "cat", "-n", NULL);
    perror("execlp");
    exit(1);
  }

  close(pb[0]);
  wait(&dummy);
  wait(&dummy);
  wait(&dummy);

}

Grading

12 points

One point for each of the following:

I went fractional here -- if you had to make three closes, and you only made 2, you got 2/3 (0.67). If you didn't check for the open of f1 failing, you only got 3/4.

Points were deducted for the following reasons: