// test fork() and pipe() // #include #include #include #include void error( const char *msg) { perror(msg); exit(1); } int main( void) { int fd[2]; if( pipe(fd) < 0) perror("pipe"); // 0 stdin, 1 stdout // fd[0] read side, fd[1] write side int pid = fork(); if( pid < 0) error("fork"); if( pid != 0) { // parent dup2(fd[1],1); // connect stdout to pipe close(fd[0]); close(fd[1]); // close unneeded descriptors // printf( "hi from parent\n"); fflush(stdout); // goes into the pipe execlp( "ls", "ls", NULL); error( "ls"); } else { // child dup2(fd[0],0); // connect stdin to pipe close(fd[0]); close(fd[1]); // close unneeded descriptors // char msg[BUFSIZ]; fgets(msg,BUFSIZ,stdin); // read from the pipe // printf( "child got: %s", msg); // write to terminal sleep(1); execlp( "cat", "cat", "-n", NULL); error( "cat"); } } /* sample run: $ ./a.out $ 1 NOTES 2 a.out 3 a9 4 fork2.c 5 pthread.c 6 pthread2.c */