// modified p4.c to use dup2() #include #include #include #include #include #include #include int main(int argc, char *argv[]) { int rc = fork(); if (rc < 0) { // fork failed; exit fprintf(stderr, "fork failed\n"); exit(1); } else if (rc == 0) { // child: redirect standard output to a file /* close(STDOUT_FILENO); open("./p4.output", O_CREAT|O_WRONLY|O_TRUNC, S_IRWXU); */ int f = open("./p4.output", O_CREAT|O_WRONLY|O_TRUNC, S_IRWXU); dup2( f, 1); // dups f onto 1 (stdout) close(f); // f no longer needed // now exec "wc"... char *myargs[3]; myargs[0] = strdup("wc"); // program: "wc" (word count) myargs[1] = strdup("p4.c"); // argument: file to count myargs[2] = NULL; // marks end of array execvp(myargs[0], myargs); // runs word count } else { // parent goes down this path (original process) int wc = wait(NULL); assert(wc >= 0); } return 0; } /* sample run: $ ./p4 fog% ls -l p4.output -rwx------ 1 perry perry 20 Sep 7 08:13 p4.output $ cat p4.output 41 143 1060 p4.c $ wc p4.c 41 143 1060 p4.c $ */