Advertisement
EXTREMEXPLOIT

Pipe Chain

Mar 22nd, 2021
711
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.46 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <semaphore.h>
  3. #include <pthread.h>
  4. #include <fcntl.h>
  5. #include <stdlib.h>
  6. #include <unistd.h>
  7. #include <wait.h>
  8. #include <string.h>
  9. #include <sys/stat.h>
  10. #include <sys/shm.h>
  11. #include <stdbool.h>
  12.  
  13. #define NPROCESSES 10
  14.  
  15. int Main2(){
  16.     srand(time(NULL)); // Hacemos la seed de nuestra función rand, se el tiempo UNIX en ese momento.
  17.     int K = rand()%50; // Rand(0, 50)
  18.     printf("Random Number: %d \n", K);
  19.     // Pipe[0]: Read    Pipe[1]: Write
  20.     int Pipe1[2]; pipe(Pipe1); // Creamos nuestra Pipe1.
  21.     int Pipe2[2]; pipe(Pipe2); // Creamos nuestra Pipe2.
  22.  
  23.     for (int i=0; i<NPROCESSES; i++)
  24.     {
  25.         if (fork() == 0)
  26.         {
  27.             if (i%2 == 0)
  28.             {
  29.                 close(Pipe1[1]); close(Pipe2[0]);
  30.                 read(Pipe1[0], &K, sizeof(K));
  31.                 K++;
  32.                 write(Pipe2[1], &K, sizeof(K));
  33.             }
  34.             else
  35.             {
  36.                 close(Pipe1[0]); close(Pipe2[1]);
  37.                 read(Pipe2[0], &K, sizeof(K));
  38.                 K++;
  39.                 write(Pipe1[1], &K, sizeof(K));
  40.             }
  41.             printf("Proces %d | K = %d \n", i, K);
  42.             exit(0);
  43.         }
  44.     }
  45.  
  46.     close(Pipe1[0]); // Cerramos el canal de lectura.
  47.     write(Pipe1[1], &K, sizeof(K)); // Escribimos el número aleatorio en la Pipe.
  48.  
  49.     for (int i=0; i<NPROCESSES; i++) wait(NULL); // Esperamos que todos los 10 procesos terminen.
  50.  
  51.     return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement