#include #include #include void setNonBlocking(int); void clearbuf(char *); void parent_handler(); int numToSpawn; int child2par[100][2]; int par2child[100][2]; main(int argc, char **argv) { // check the command line input to make sure it's pairs of numbers if (argc % 2 == 0 || argc == 1) { printf("input must be a set of pairs of numbers"); exit(0); } int i = 1; int j, k; numToSpawn = (argc - 1) / 2; printf("num to spawn=%d\n", numToSpawn); int parent_pid = getpid(); signal(SIGUSR1, parent_handler); int length; char buf[1024]; char buf2[1024]; int position = 1; int pid; int m, n, mm, nn; for(i = 0; i < numToSpawn; i++) { // open one pipe to read from child if (pipe(child2par[i]) == -1) perror("open pipe"); //open second pipe to write to child if (pipe(par2child[i]) == -1) perror("open pipe"); setNonBlocking(child2par[i][0]); sscanf(argv[2*i + 1], "%d", &m); sscanf(argv[2*i + 2], "%d", &n); printf("m=%d, n=%d\n", m, n); pid = fork(); switch(pid){ case -1: perror("fork"); break; case 0: //child sleep(1); printf("entered child\n"); close(child2par[i][0]); close(par2child[i][1]); mm=m; nn=n; while(nn>0){ clearbuf(buf); sprintf(buf, "%d %d", mm, nn); // printf("buf=%s\n",buf); length = strlen(buf); if (write(child2par[i][1], buf, length) != length) perror("write to pipe"); kill(parent_pid,SIGUSR1); clearbuf(buf2); read(par2child[i][0], buf2, 1024); // printf("buf2=%s\n",buf2); mm=nn; sscanf(buf2, "%d", &nn); } printf("GCD(%d, %d)= %d\n", m, n, mm); fflush(stdout); exit(i); break; default: //parent // printf("entered parent\n"); //sleep(1); close(child2par[i][1]); close(par2child[i][0]); }//switch }//for for (i=0; i< numToSpawn; i++) { k= wait(&j); printf("waiting i=%d, child pid=%d, j=%d\n",i,k,j); } printf("Parent dies\n"); } void setNonBlocking(int fd) { int val; if ((val = fcntl(fd, F_GETFL, 0)) < 0) perror("fcntl F_GETFL error"); val |= O_NONBLOCK; // turn on flags if (fcntl(fd, F_SETFL, val)<0) perror("fcntl F_SETFL error"); } void parent_handler() { signal(SIGUSR1, parent_handler); char outbuf[1024]; int a, b, c, i, n, length; int work=1; while (work ==1) { work=0; for (i = 0; i < numToSpawn; i++) { n = read(child2par[i][0], outbuf, 1024); if (n != 0) { work=1; sscanf(outbuf, "%d %d", &a, &b); c = a - b; while (c >= b) c = c - b; clearbuf(outbuf); sprintf(outbuf, "%d", c); length = strlen(outbuf); if (write(par2child[i][1], outbuf, length) != length) perror("write to pipe"); } } } } void clearbuf(char * b){ int i; for (i=0; i<1024; i++) b[i] = '\0'; }