/* Demonstrate what happens when the Child gets killed if we have */ /* a parent piping to a Child who in turn pipes to a grandchild. */ #include #include #include #include main(argc,argv) int argc; char *argv[]; {pid_t IsParent,IsChild; int WriteError=1,ReadError=1,Pipefd[2],Pipefd2[2],N; div_t Result; printf("!\n"); pipe(Pipefd); IsParent=fork(); if (IsParent) { dup2(Pipefd[1],1); close(Pipefd[1]); close(Pipefd[0]); N=0; while (1) { /* Continually write Numbers to the Pipe */ if ((WriteError=write(1,&N,sizeof(int)))<0) { perror("Parent Failed due to"); exit(1); } Result=div(N++,10); fprintf(stderr,"Parent Sends %d\n",N); sleep(1); } } else { /* Child receives thru the pipe */ pipe(Pipefd2); IsChild=fork(); if (IsChild>0) { dup2(Pipefd[0],0); close(Pipefd[1]); close(Pipefd[0]); dup2(Pipefd2[1],1); close(Pipefd2[1]); close(Pipefd2[0]); while (ReadError) { if ((ReadError=read(0,&N,sizeof(int)))<0){ /* Continually read Numbers from the Pipe */ perror("Got a -1"); exit(1); } write(1,&N,sizeof(int)); fprintf(stderr," Child processes %d - Read Result: %d\n",N,ReadError); sleep(2); /* Slow Things Down */ } } else { /* GrandChild */ dup2(Pipefd2[0],0); close(Pipefd2[1]); close(Pipefd2[0]); while (ReadError) { if ((ReadError=read(0,&N,sizeof(int)))<0){ /* Continually read Numbers from the Pipe */ perror("Got a -1"); exit(1); } fprintf(stderr," GrandChild Received %d - Read Result: %d\n",N,ReadError); if (N==5) kill(getppid(),9); } } } }