Advertisement
Guest User

Untitled

a guest
Nov 25th, 2015
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <iostream>
  3. #include <sys/types.h>
  4. #include <sys/wait.h>
  5. #include <stdio.h>
  6. #include <fcntl.h>
  7. #include <stdint.h>
  8. #include <stdlib.h>
  9.  
  10. void process_turn(unsigned long N, int pid, int *fdto, int *fdfrom) {
  11. close(fdto[0]);
  12. close(fdfrom[1]);
  13. unsigned long curnum = pid;
  14. while(curnum <= N) {
  15. read(fdfrom[0], &curnum, sizeof(curnum));
  16. if (curnum <= N)
  17. std::cout << pid << ' ' << curnum << std::endl;
  18. curnum++;
  19. write(fdto[1], &curnum, sizeof(curnum));
  20. }
  21. close(fdfrom[0]);
  22. close(fdto[1]);
  23. exit(0);
  24. }
  25.  
  26. int main(int argc, char* argv[]) {
  27. unsigned long N = strtol(argv[1], NULL, 10);
  28. int fd1[2];
  29. int fd2[2];
  30. pipe(fd1);
  31. pipe(fd2);
  32.  
  33. int pid = fork();
  34.  
  35. if(!pid) {
  36. pid = 2;
  37. int start = 1;
  38. write(fd1[1], &start, sizeof(start));
  39. process_turn(N, pid, fd1, fd2);
  40. } else {
  41. pid = fork();
  42. if (pid) {
  43. close(fd1[0]);
  44. close(fd1[1]);
  45. close(fd2[0]);
  46. close(fd2[1]);
  47. wait(NULL);
  48. wait(NULL);
  49. exit(0);
  50. } else {
  51. pid = 1;
  52. process_turn(N, pid, fd2, fd1);
  53. }
  54. }
  55. return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement