// pipe.c example modified to use execlp() // // parent should really create two children and wait for them, // otherwise output is not synchronized with the shell // file descriptors: // // 0 = stdin, read using scanf() // 1 = stdout, write using printf() // 2 = stderr, write using fprintf( stderr, ...) // // fd[0] read, input // fd[1] write, output #include #include int main( void) { int fd[2]; // for pipe file descriptors if( pipe(fd) < 0) { perror("pipe"); return 1; } int pid = fork(); if( pid < 0) { perror("fork"); return 1; } if( pid == 0) // child { dup2( fd[0], 0); // make stdin come from pipe close(fd[0]); close(fd[1]); // fd no longer needed, close it /* int x = 0; scanf("%d",&x); // read from parent printf( "x = %d\n", x); */ execlp( "rev", "rev", NULL); // should not return perror( "rev"); } else // parent { dup2( fd[1], 1); // make stdout go to pipe close(fd[0]); close(fd[1]); // fd no longer needed, close it /* printf( "%d", 123); // write to child */ execlp( "date", "date", NULL); perror( "date"); } return 0; } /* sample run: $ make gcc -Wall -o pipe pipe.c $ ./pipe $ 2202 TDE 54:30:80 7 peS deW */