// test fork() and pipe() // #include #include #include #include int x = 0; // not shared with child void error( const char *msg) { perror(msg); exit(1); } int main( void) { #ifndef PART1 int fd[2]; if( pipe(fd) < 0) perror("pipe"); // 0 stdin // 1 stdout // fd[0] read side // fd[1] write side dup2(fd[0],0); // connect stdin to pipe dup2(fd[1],1); // connect stdout to pipe close(fd[0]); close(fd[1]); // close unneeded descriptors #endif int pid = fork(); if( pid < 0) error("fork"); if( pid == 0) { // child #ifdef PART1 for( int i = 0; i < 5; ++i) { printf( "child %i %i\n", getpid(), ++x); sleep(1); } execlp( "ls", "ls", "-l", "Makefile", NULL); error("ls"); #else printf( "hi from child\n"); // goes into the pipe return 66; #endif } else { // parent #ifdef PART1 for( int i = 0; i < 5; ++i) { printf( "parent %i %i\n", getpid(), ++x); sleep(2); } #else char msg[BUFSIZ]; fgets(msg,BUFSIZ,stdin); // read from the pipe fprintf( stderr, "parent got: %s", msg); // write to terminal int s; // for child exit status wait(&s); fprintf( stderr, "s = %i, exit = %i\n", s, WEXITSTATUS(s) ); // write to terminal #endif } }