jfcmacro

jerarquiaProcesos.cpp

Mar 15th, 2019
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. #include <iostream>
  2. #include <sys/types.h>
  3. #include <sys/wait.h>
  4. #include <sys/ipc.h>
  5. #include <sys/sem.h>
  6. #include <cstdlib>
  7. #include <cerrno>
  8. #include <cstring>
  9. #include <unistd.h>
  10.  
  11. using namespace std;
  12.  
  13. void demonio(int);
  14. void cliente(int);
  15.  
  16. // crearSemaforo <keysem>
  17. int
  18. main(int argc, char *argv[]) {
  19.  
  20.   int semid = semget(IPC_PRIVATE, 1, IPC_CREAT | IPC_EXCL| 0660);
  21.  
  22.   if (semid == -1) {
  23.     cerr << "Error abriendo el semaforo: "
  24.      << strerror(errno) << endl;
  25.     return EXIT_FAILURE;
  26.   }
  27.  
  28.   int val = 0;
  29.  
  30.   if (semctl(semid, 0, SETVAL, val) == -1) {
  31.     cerr << "Error estableciendo el valor del semaforo: "
  32.      << strerror(errno) << endl;
  33.     return EXIT_FAILURE;
  34.   }
  35.  
  36.   pid_t pDem, pCln;
  37.  
  38.   if ((pDem = fork()) == 0) {
  39.     demonio(semid);
  40.   }
  41.   else if ((pCln = fork()) == 0) {
  42.     cliente(semid);
  43.   }
  44.   else {
  45.     int status;
  46.     waitpid(pDem, &status, 0);
  47.     waitpid(pCln, &status, 0);
  48.   }
  49.  
  50.   semctl(semid, 0, IPC_RMID);
  51.  
  52.   return EXIT_SUCCESS;
  53. }
  54.  
  55. void demonio(int semid) {
  56.   for (;;) {
  57.     struct sembuf ops[1]; //  = { { 0, -1, 0} };
  58.  
  59.     // wait(sem)
  60.     ops[0].sem_num = 0;
  61.     ops[0].sem_op  = -1;
  62.     ops[0].sem_flg = 0;
  63.     cout << "Esperando por mensajes de impresion" << endl;
  64.     semop(semid, ops, 1);
  65.     cout << "Operacion recibida" << endl;
  66.   }
  67.  
  68. }
  69.  
  70. void cliente(int semid) {
  71.   for (;;) {
  72.     struct sembuf ops[1]; //  = { { 0, -1, 0} };
  73.  
  74.     sleep(10);
  75.     ops[0].sem_num = 0;
  76.     ops[0].sem_op  = 1;
  77.     ops[0].sem_flg = 0;
  78.     cout << "Enviando evento" << endl;
  79.     semop(semid, ops, 1);
  80.   }
  81.  
  82. }
Advertisement
Add Comment
Please, Sign In to add comment