// file: ls_less.c // // Synopsis: Simple illustration of pipe between 2 processes // from [Jumpstart]. // // Executes "ls" and pipes output to "less". // (1) Creates pipe // (2) Forks // (3) Child: redirect output to pipe, then exec "ls" // (4) Parent: redirect input to pipe, then exec "less" // // REMARK: THIS PROGRAM WORKS ON BOTH CYGWIN and SOLARIS. // Chee Yap #include #include main() { int pid; int pipev[2]; if (pipe(pipev) == -1) perror("pipe"); pid = fork(); if (pid == 0) { /* child */ char *argv[] = {"ls", "/etc", ".", NULL}; dup2(pipev[1], STDOUT_FILENO); // redirect output of ls close(pipev[0]); close(pipev[1]); execvp("ls", argv); perror("ls"); } else if (pid >0) { /* parent */ dup2(pipev[0], STDIN_FILENO); // redirect input of less close(pipev[0]); close(pipev[1]); execlp("less", "less", NULL); perror("less"); } else perror("fork"); printf("finish\n"); exit(0); }