ex2.c (2135B)
1 #include <sys/wait.h> 2 3 #include <err.h> 4 #include <stdio.h> 5 #include <stdlib.h> 6 #include <string.h> 7 #include <unistd.h> 8 9 /* 10 * Εργαστήριο ΛΣ2 (Δ6) / Εργασία 1: Άσκηση 2 / 2020-2021 11 * Ονοματεπώνυμο: Χρήστος Μαργιώλης 12 * ΑΜ: 19390133 13 * Τρόπος μεταγλώττισης: `cc ex2.c -o ex2` 14 */ 15 16 /* 17 * Print a process' info. `n` indicates which process is being 18 * printed -- for example `printproc(2)` will print P2. 19 */ 20 static void 21 printproc(int n) 22 { 23 printf("p: %d\tpid: %d\tppid: %d\n", n, getpid(), getppid()); 24 } 25 26 int 27 main(int argc, char *argv[]) 28 { 29 char buf[32]; /* Message buffer */ 30 int fd[2]; /* Pipe(2) file descriptors */ 31 int n; /* Bytes returned from read(2) */ 32 int i = 3; /* P2 will create 3 child procs */ 33 34 /* Create pipe */ 35 if (pipe(fd) < 0) 36 err(1, "pipe"); 37 38 printproc(0); 39 40 /* Create P1 */ 41 switch (fork()) { 42 case -1: 43 err(1, "fork"); 44 case 0: 45 printproc(1); 46 (void)strcpy(buf, "Hello from your first child\n"); 47 /* Close the read fd and send message to P0 */ 48 (void)close(fd[0]); 49 if (write(fd[1], buf, sizeof(buf)) != sizeof(buf)) 50 err(1, "write"); 51 exit(EXIT_SUCCESS); 52 default: 53 /* Close the write fd and receive message from P1 */ 54 (void)close(fd[1]); 55 if ((n = read(fd[0], buf, sizeof(buf))) != sizeof(buf)) 56 err(1, "read"); 57 /* Print the message to stdout */ 58 if (write(STDOUT_FILENO, buf, n) != n) 59 err(1, "write"); 60 if (wait(NULL) < 0) 61 err(1, "wait"); 62 /* Create P2 */ 63 switch (fork()) { 64 case -1: 65 err(1, "fork"); 66 case 0: 67 printproc(2); 68 /* create P3, P4 and P5 */ 69 while (i--) { 70 switch (fork()) { 71 case -1: 72 err(1, "fork"); 73 case 0: 74 printproc(2 + i + 1); 75 exit(EXIT_SUCCESS); 76 default: 77 /* Wait for all children to exit first */ 78 if (wait(NULL) < 0) 79 err(1, "wait"); 80 } 81 } 82 exit(EXIT_SUCCESS); 83 default: 84 /* wait for P2 to exit */ 85 if (wait(NULL) < 0) 86 err(1, "wait"); 87 } 88 /* 89 * Finally, the parent process executes ps(1) after 90 * everything else has exited 91 */ 92 if (execl("/bin/ps", "ps", NULL) < 0) 93 err(1, "execl"); 94 } 95 96 return 0; 97 }