Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <inttypes.h>
- #include <fcntl.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <unistd.h>
- int main(int argc, char ** argv) {
- int n = (int) strtol(argv[1], NULL, 10), cur_n = 0;
- int filedes_1[2];
- pipe(filedes_1);
- int filedes_2[2];
- pipe(filedes_2);
- FILE *output_1 = fdopen(filedes_1[1], "w");
- FILE *output_2 = fdopen(filedes_2[1], "w");
- fprintf(output_2, "1 ");
- fflush(output_2);
- pid_t child_1 = fork();
- if (child_1 == 0) {
- FILE * input = fdopen(filedes_2[0], "r");
- close(filedes_1[0]);
- close(filedes_2[1]);
- while (fscanf(input, "%d", &cur_n) != EOF) {
- if (cur_n == n) {
- _exit(0);
- }
- printf("1 ");
- printf("%d\n", cur_n);
- fprintf(output_1, "%d ", ++cur_n);
- fflush(stdout);
- fflush(output_1);
- }
- close(filedes_1[1]);
- close(filedes_2[0]);
- fclose(input);
- fclose(output_1);
- _exit(0);
- }
- pid_t child_2 = fork();
- if (child_2 == 0) {
- FILE * input = fdopen(filedes_1[0], "r");
- close(filedes_1[1]);
- close(filedes_2[0]);
- while (fscanf(input, "%d", &cur_n) != EOF) {
- if (cur_n == n) {
- _exit(0);
- }
- printf("2 ");
- printf("%d\n", cur_n);
- fprintf(output_2, "%d ", ++cur_n);
- fflush(stdout);
- fflush(output_2);
- }
- close(filedes_1[0]);
- close(filedes_2[1]);
- fclose(input);
- fclose(output_2);
- _exit(0);
- }
- close(filedes_1[0]);
- close(filedes_1[1]);
- close(filedes_2[0]);
- close(filedes_2[1]);
- wait(NULL);
- wait(NULL);
- printf("Done\n");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement