// test pthreads and pipe // #include #include #include #include int x = 0; // shared with all threads void error( const char *msg) { perror(msg); exit(1); } void *f(void *p) { #ifdef PART1 for( int i = 0; i < 5; ++i) { printf( "f %i %i\n", getpid(), ++x); sleep(1); } return 0; #else printf( "hi from f\n"); fflush(stdout); // goes into the pipe static int v = 99; return &v; #endif } // int a[10]; // a is pointer to a[0], a == &a[0] // f(0) calls f, f is pointer to f(), f == &f int main( void) { #ifndef PART1 int fd[2]; if( pipe(fd) < 0) perror("pipe"); 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 pthread_t t; if( pthread_create( &t, 0, f, 0) != 0) error( "pthread_create"); #ifdef PART1 for( int i = 0; i < 5; ++i) { printf( "main %i %i\n", getpid(), ++x); sleep(2); } #else char msg[BUFSIZ]; fgets(msg,BUFSIZ,stdin); // read from the pipe fprintf( stderr, "main got: %s", msg); // write to terminal int *v; // for thread return value pthread_join( t, (void**)&v); fprintf( stderr, "*v = %i\n", *v); #endif }