#include #include /* for fork, getpid */ #include /* for the poll call */ #include /* for rand*/ void sleepabit(pid_t mypid, int fd) { int naptime; char abuf[200]; int len; naptime = rand() % 5+1; len = sprintf(abuf,"%d is sleeping %d written to %d",mypid,naptime,fd); /* printf("%d is sleeping %d, written to %d\n",mypid,naptime,fd); */ write(fd,abuf,len); sleep(naptime); } main() { pid_t mypid,pid; int fd[2]; char buf[200]; int len; int i,j,count; struct pollfd lines[3]; int pollres; for (i=0;i<3;i++){ if (0 != pipe(fd) ) { printf("We had an error making the pipe\n"); exit (-1); } if ( 0 == (pid = fork())) { /* the child code for child i */ mypid=getpid(); printf("After the fork-child, I am %d\n",mypid); srand(mypid); close(fd[0]); sleep(1); for (j=0;j<3;j++) { sleepabit(mypid,fd[1]); } /* printf("good by from pid %d\n",mypid); */ exit(1); } else { mypid=getpid(); printf("After the fork-parent, I am %d\n",mypid); close(fd[1]); lines[i].fd = fd[0]; lines[i].events = POLLIN; lines[i].revents = 0; } } printf("Parent here:\n\n"); count = 0; for (i=0;i<3;i++) { printf("We will check fd=%d\n",lines[i].fd); } printf("\n"); while (count < 9) { pollres=poll(lines,3,-1); switch (pollres) { case 0: printf("A timeout has occured, Not likely but here it is\n"); break; case -1: printf("An error has occured, exiting \n"); exit(-1); default: for (j=0;j<3;j++) { if (lines[j].revents & POLLIN) { count ++; len = read(lines[j].fd,buf,sizeof(buf)); buf[len]=0; printf("A child says: <<%s>>, event %d\n",buf,count); lines[j].revents=0; buf[0]=(char)0; } lines[j].revents=0; } } } }