Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <inttypes.h>
- #include <stdint.h>
- #include <fcntl.h>
- int pingpong(int fdr, int fdw, int id, int max_num){
- while (1) {
- int x;
- if (read(fdr, &x, sizeof(x)) == 0) {
- return(0);
- }
- printf("%d %d\n", id, x);
- fflush(stdout);;
- ++x;
- if (x == max_num) {
- return(0);
- }
- write(fdw, &x, sizeof(x));
- }
- }
- int main(int argc, char **argv)
- {
- int max_num = strtol(argv[1], NULL, 10);
- if (max_num <= 1) {
- _exit(0);
- }
- int fd12[2];
- int fd21[2];
- if (pipe(fd12) < 0) {
- perror("pipe");
- _exit(1);
- }
- if (pipe(fd21) < 0) {
- perror("pipe");
- _exit(1);
- }
- int pid1, pid2;
- if ((pid1 = fork()) < 0) {
- perror("fork");
- _exit(1);
- }
- if (pid1 == 0){
- close(fd12[0]);
- close(fd21[1]);
- pingpong(fd21[0], fd12[1], 1, max_num);
- close(fd21[0]);
- close(fd12[1]);
- _exit(0);
- }
- if ((pid2 = fork()) < 0) {
- perror("fork");
- _exit(1);
- }
- if (pid2 == 0){
- close(fd21[0]);
- close(fd12[1]);
- pingpong(fd12[0], fd21[1], 2, max_num);
- close(fd12[0]);
- close(fd21[1]);
- _exit(0);
- }
- int x = 1;
- write(fd21[1], &x, sizeof(x));
- close(fd12[0]);
- close(fd21[1]);
- close(fd21[0]);
- close(fd12[1]);
- wait(NULL);
- wait(NULL);
- printf("%s\n", "Done");
- fflush(stdout);
- _exit(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement