Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <unistd.h>
- #include <iostream>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <stdio.h>
- #include <fcntl.h>
- #include <stdint.h>
- #include <stdlib.h>
- void process_turn(unsigned long N, int pid, int *fdto, int *fdfrom) {
- close(fdto[0]);
- close(fdfrom[1]);
- unsigned long curnum = pid;
- while(curnum <= N) {
- read(fdfrom[0], &curnum, sizeof(curnum));
- if (curnum <= N)
- std::cout << pid << ' ' << curnum << std::endl;
- curnum++;
- write(fdto[1], &curnum, sizeof(curnum));
- }
- close(fdfrom[0]);
- close(fdto[1]);
- exit(0);
- }
- int main(int argc, char* argv[]) {
- unsigned long N = strtol(argv[1], NULL, 10);
- int fd1[2];
- int fd2[2];
- pipe(fd1);
- pipe(fd2);
- int pid = fork();
- if(!pid) {
- pid = 2;
- int start = 1;
- write(fd1[1], &start, sizeof(start));
- process_turn(N, pid, fd1, fd2);
- } else {
- pid = fork();
- if (pid) {
- close(fd1[0]);
- close(fd1[1]);
- close(fd2[0]);
- close(fd2[1]);
- wait(NULL);
- wait(NULL);
- exit(0);
- } else {
- pid = 1;
- process_turn(N, pid, fd2, fd1);
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement