//HW2 #include #include #include #include #include #include #include int main(int argc, char ** argv) { time_t t0, t1; clock_t c0, c1; t0 = time(NULL); c0 = clock(); int check = 1; int ptoc[2]; int ctop[2]; pid_t pid; if(pipe(ctop) != 0 || pipe(ptoc) != 0){ printf("Pipe failed"); exit(-1); } while(check < argc){ int a = 0; int b = 0; pid = getpid(); printf("Parent Process ID: %d\n", pid); a = atoi(argv[check++]); b = atoi(argv[check++]); int a1 = a; int b1 = b; int tmp1; if(b > a){ tmp1 = a; a = b; b = tmp1; } switch(fork()){ case -1: printf("ERROR"); break; case 0: pid = getpid(); printf("Child Process ID: %d\n", pid); int mod = -1; char buff[10]; while(mod != 0 && mod != 1){ sprintf(buff, "%d, %d", a, b); write(ctop[1], &buff, sizeof(buff)); read(ptoc[0], &mod, sizeof(mod)); // printf("The GCD of %d and %d is %d\n",a1, b1, mod); printf("%d = %d * %d + %d\n", a, b, (a/b), mod); if(b < (a/b)){ b = (a/b); a = mod; } } t1 = time(NULL); c1 = clock(); printf("Elapsed time since January 1, 1970:\t%d\n",(long)(t1)); printf("Elapsed clock time:\t%d\n",(int)(c1)); close(ctop[1]); exit(0); break; } printf("PARENT PROCESS\n"); setFlag(ctop[0], O_NONBLOCK); char buff[10]; int num; int tmp; read(ctop[0], &buff, sizeof(buff)); sscanf(buff, "%d, %d", &a, &b); // num = gcd(&a, &b); if(b > a){ tmp = a; a = b; b = tmp; } num = a % b; write(ptoc[1], &num, sizeof(num)); // WRONG close(ptoc[1]); } // t1 = time(NULL); //get time since Jan 1, 1970 // c1 = clock(); // printf("Elapsed time since January 1, 1970:\t%d\n",(long)(t1 - t0)); // printf("Elapsed clock time:\t%d\n",(int)(c1 - c0)); close(ctop[0]); return 0; } setFlag(int fd, int flags) { int val; if ((val = fcntl(fd, F_GETFL, 0)) < 0) perror("fcntl F_GETFL error"); val |= flags; if(fcntl(fd, F_SETFL, val) < 0 ) perror("fcntl F_GETFL error"); } int gcd(int *a, int *b) { int tmp; while(((*a) % (*b) != 0) && ((*a) % (*b) != 1)) { if((*b) > (*a)){ tmp = (*a); (*a) = (*b); (*b) = tmp; } (*a) %= (*b); if((*b) > (*a)){ tmp = (*a); (*a) = (*b); (*b) = tmp; } } if(((*a) % (*b)) == 0) return (int)(*b); else return 1; }