#include #include #include #include #include #include #include #include #include #define FALSE 0 #define TRUE 1 int MyHeight; char *MyLabel, HeightArg[10], LeftLabelArg[20], RightLabelArg[20]; pid_t pidLeft, pidRight; int fd; int LeftPipe[2]; int RightPipe[2]; int RootProcess=FALSE; int LeafProcess=FALSE; int MiddleProcess=FALSE; int n; char msg[100]; char buf[100]; void MyCode(); void SIGhandler(int); main(argc, argv) int argc; char *argv[]; { if (argc == 3) { MyHeight = atoi(argv[1]); if (MyHeight == 0) LeafProcess=TRUE; else MiddleProcess=TRUE; MyLabel = argv[2]; printf("NEW process %d strted: %d, %s\n", getpid(), MyHeight, MyLabel); } else { printf ("Root Process %d Started\n", getpid()); RootProcess= TRUE; MyLabel=""; if (argc==2) MyHeight = atoi(argv[1]); else MyHeight = 1; if ( (fd = open("BinTreeLogFile", O_TRUNC | O_CREAT | O_WRONLY, 0777)) < 0){ printf("can not open LogFile..\n"); exit(-1); } } signal(SIGQUIT, SIGhandler); if (MyHeight > 0){ sprintf(HeightArg,"%d", MyHeight-1); sprintf(LeftLabelArg, "%s%s",MyLabel, "0"); sprintf(RightLabelArg, "%s%s",MyLabel, "1"); pipe(LeftPipe); pipe(RightPipe); if ( (pidLeft = fork()) == 0) { dup2(LeftPipe[0], 0); close(LeftPipe[0]); close(LeftPipe[1]); close(RightPipe[0]); close(RightPipe[1]); execl("./BinTree", "BinTree", HeightArg, LeftLabelArg, 0); printf("exec ERROR"); fflush(stdout); exit(1); } else { close(LeftPipe[0]); if ( (pidRight = fork()) == 0) { dup2(RightPipe[0], 0); close(RightPipe[0]); close(RightPipe[1]); close(LeftPipe[0]); close(LeftPipe[1]); execl("./BinTree", "BinTree", HeightArg, RightLabelArg, 0); perror("exec"); exit(1); } close(RightPipe[0]); sleep(1); MyCode(); } } else { sleep(1); MyCode(); } } void MyCode() { if (LeafProcess) { for(;;){ cleanup(); n =read(0,buf,sizeof(buf)); /* if (n==0) { printf("leaf.. no more read\n"); exit(0); } */ sprintf(msg,"<%s>:%s\n", MyLabel, buf); write(1,msg,strlen(msg)); write(3, msg, strlen(msg)); } } else if (RootProcess) { for(;;){ cleanup(); n=read(0,buf, sizeof(buf)); if (n==0) { printf("Root exiting...\n"); kill(pidLeft,SIGQUIT); kill(pidRight,SIGQUIT); exit(0); } sprintf(msg,"<%s>:%s\n", "Root", buf); write(3, msg, strlen(msg)); write(LeftPipe[1],buf,n); write(RightPipe[1],buf,n); } } else if (MiddleProcess){ for(;;){ cleanup(); n=read(0,buf,sizeof(buf)); /* if (n==0) { printf("middle.. no more read\n"); exit(0); } */ write(LeftPipe[1],buf, n); write(RightPipe[1],buf, n); } } } cleanup() { int i; for(i=0; i<100; i++) buf[i]=NULL; } void SIGhandler(int sig) { if (MiddleProcess){ kill(pidLeft,SIGQUIT); kill(pidRight,SIGQUIT); } exit(0); }