// file: ls_SPOOL.c // // Synopsis: Simple illustration of redrection of output // // Main process forks. // Child Process: (1) creats a file "SPOOL" // (2) make SPOOL the standard output // (3) close current standard output // (4) exec "ls /etc ." (listing 2 dirs) // Parent Process: Wait on child // // REMARK: THIS PROGRAM WORKS in CYGWIN and SOLARIS. // Chee Yap #include #include #include #include #include main() { char *prog = "ls"; char *argv[] = {"ls", "/etc", ".", NULL}; int pid; printf("Before execute\n"); pid = fork(); if (pid==0) { /* child */ int f; if ((f=creat("SPOOL", S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) == -1) perror("SPOOL"); dup2(f, STDOUT_FILENO); close(f); // original not needed after dup2 execvp(prog, argv); perror(prog); } else if (pid>0) /* wait for child */ wait(NULL); else perror("execute"); printf("After execute\n"); exit(0); }