Created
June 25, 2016 16:28
-
-
Save alibitek/0e1a22b8ea9a08debe54d656baee5dca to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <unistd.h> | |
#include <stdlib.h> | |
#include <errno.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
#define N 6 | |
#define K 2 | |
int main(int argc, char* argv[]) | |
{ | |
int i, n = 1, p[N][2]; | |
printf("Creating pipes\n"); | |
for (i = 0; i < N; i++) | |
{ | |
if (pipe(p[i]) == -1) | |
{ | |
perror("Cannot open pipe\n"); | |
exit(1); | |
} | |
} | |
write(p[0][1], &n, sizeof(int)); | |
printf("Compute in each child process\n"); | |
for (i = 0; i < N; i++) | |
{ | |
switch(fork()) | |
{ | |
case -1: /* Handle error */ | |
{ | |
perror("Cannot fork"); | |
exit(-1); | |
break; | |
} | |
case 0: /* Child */ | |
{ | |
//printf("Child %d\n", i+1); | |
read(p[i][0], &n, sizeof(int)); | |
n++; | |
printf("Child %d, n=%d\n", i+1, n); | |
// K = 1 | |
// (0 + 1) % 6 = 1 | |
// (1 + 1) % 6 = 2 | |
// (2 + 1) % 6 = 3 | |
// (3 + 1) % 6 = 4 | |
// (4 + 1) % 6 = 5 | |
// (5 + 1) % 6 = 0 | |
// K = 2 | |
// (0 + 2) % 6 = 2 | |
// (1 + 2) % 6 = 3 | |
// (2 + 2) % 6 = 4 | |
// (3 + 2) % 6 = 5 | |
// (4 + 2) % 6 = 0 | |
// (5 + 2) % 6 = 1 | |
printf("n=%d, i=%d, K=%d, N=%d, (i + K) \% N = %d\n", n, i, K, N, (i + K) % N); | |
write(p[(i + K) % N][1], &n, sizeof(int)); | |
exit(0); | |
} | |
default: /* Parent */ | |
break; | |
} | |
} | |
printf("Waiting for all child processes to finish\n"); | |
for (i = 0; i < N; i++) | |
{ | |
wait(0); | |
} | |
read(p[0][0], &n, sizeof(int)); | |
printf("%d\n", n); | |
for (i = 0; i < N; i++) | |
{ | |
close(p[i][0]); | |
close(p[i][1]); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment