Advertisement
Guest User

Untitled

a guest
Dec 16th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.14 KB | None | 0 0
  1. #include <zconf.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <memory.h>
  5. #include <sys/wait.h>
  6. #include <ctype.h>
  7.  
  8. int main(int argc, char *argv[]) {
  9.     enum { BUF_SIZE = 16 };
  10.     int fd0[2];
  11.     pipe(fd0);
  12.     pid_t  p1 = fork();
  13.     if (p1 < 0) {
  14.         return 1;
  15.     } else if (p1 == 0) {
  16.         int fd1[2];
  17.         pipe(fd1);
  18.         pid_t p2 = fork();
  19.         if (p2 <  0) {
  20.             return 1;
  21.         } else if (p2 == 0) {
  22.             close(fd0[0]);
  23.             close(fd1[1]);
  24.             if (dup2(fd1[0], 0) < 0) {
  25.  
  26.                 return 1;
  27.             }
  28.  
  29.             if (dup2(fd0[1], 1) < 0) {
  30.                 return 1;
  31.             }
  32.  
  33.             close(fd1[0]);
  34.             close(fd0[1]);
  35.             execlp(argv[3], argv[3], NULL);
  36.             return 1;
  37.         } else {
  38.             close(fd0[0]);
  39.             close(fd0[1]);
  40.             close(fd1[0]);
  41.             int count = atoi(argv[1]);
  42.             int mod = atoi(argv[2]);
  43.             for (int i = 1; i <= count; i++) {
  44.                 dprintf(fd1[1], "%llu\n", (unsigned long long) (i * i) % mod);
  45.             }
  46.             close((fd1[1]));
  47.             wait(NULL);
  48.             return 0;
  49.         }
  50.     } else {
  51.         close(fd0[1]);
  52.  
  53.     }
  54.  
  55.     pid_t  p3 = fork();
  56.     if (p3 < 0) {
  57.         return 1;
  58.     } else if (p3 == 0) {
  59.         pid_t p4 = fork();
  60.         if (p4 <  0) {
  61.             return 1;
  62.         } else if (p4 == 0) {
  63.             close(fd0[1]);
  64.             dup2(fd0[0], 0);
  65.             close(fd0[0]);
  66.             char buf[BUF_SIZE] = {0};
  67.             while (fgets(buf, BUF_SIZE, stdin) != NULL) {
  68.                 for (int i = 0; i < BUF_SIZE && buf[i] != '\0'; i++) {
  69.                     if (isspace(buf[i])) {
  70.                         buf[i] = '\n';
  71.                     }
  72.                 }
  73.                 printf("%s", buf);
  74.                 fflush(stdout);
  75.             }
  76.             exit(0);
  77.         } else {
  78.             close(fd0[0]);
  79.             close(fd0[1]);
  80.             wait(NULL);
  81.         }
  82.     } else {
  83.         close(fd0[0]);
  84.         wait(NULL);
  85.         wait(NULL);
  86.         printf("0\n");
  87.     }
  88.  
  89.     return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement