#include #include #include void setNonBlocking(int); void parent_handler(); int count = 0; int pipesin[1]; int pipesout[1]; 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; int parent_pid = getpid(); signal(SIGUSR1, parent_handler); int pipev[2]; int pipev2[2]; int length; char buf[1024]; char buf2[1024]; int position = 1; int pid; int m, n, next, last; // open one pipe to read from child if (pipe(pipev) == -1) perror("open pipe"); //open second pipe to write to child if (pipe(pipev2) == -1) perror("open pipe"); //pipesin[count] = pipev[0]; //pipesout[count] = pipev2[1]; //setNonBlocking(pipesin[count]); count++; //close(pipev[1]); //close(pipev2[0]); sscanf(argv[position], "%d", &m); sscanf(argv[position + 1], "%d", &n); pid = fork(); /* error */ if (pid < 0) perror("fork"); /* child */ else if (pid == 0) { sprintf(buf, "%s %s", m, n); length = strlen(buf); if (write(pipev[1], buf, length) != length) perror("write to pipe"); next = m; last = n; while(1) { next = last; read(pipev2[0], buf2, 1024); sscanf(buf2, "%d", &last); if (last == 0) { printf("GCD(%d, %d) = %d ", m, n, next); exit(0); } sprintf(buf, "%d %d", next, last); if (write(pipev[1], buf, length) != length) perror("write to pipe"); kill(parent_pid, SIGUSR1); } } else { wait(pid); exit(0); } } 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; for (i = 0; i < count; i++) { n = read(pipesin[i], outbuf, 1024); if (n != 0) break; } sscanf(outbuf, "%d %d", &a, &b); c = a - b; while (c >= b) c = c - b; sprintf(outbuf, "%d", c); length = strlen(outbuf); if (write(pipesout[count], outbuf, length) != length) perror("write to pipe"); }