jfcmacro icon

jerarquiaProcesos.cpp

jfcmacro | PRO | 03/15/19 04:35:36 PM UTC | 0 ⭐ | 340 👁️ | Never ⏰ | []
C++ |

1.49 KB

|

None

|

0 👍

/

0 👎

#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <cstdlib>
#include <cerrno>
#include <cstring>
#include <unistd.h>
 
using namespace std;
 
void demonio(int);
void cliente(int);
 
// crearSemaforo <keysem>
int
main(int argc, char *argv[]) {
 
  int semid = semget(IPC_PRIVATE, 1, IPC_CREAT | IPC_EXCL| 0660);
 
  if (semid == -1) {
    cerr << "Error abriendo el semaforo: "
     << strerror(errno) << endl;
    return EXIT_FAILURE;
  }
 
  int val = 0;
 
  if (semctl(semid, 0, SETVAL, val) == -1) {
    cerr << "Error estableciendo el valor del semaforo: "
     << strerror(errno) << endl;
    return EXIT_FAILURE;
  }
 
  pid_t pDem, pCln;
 
  if ((pDem = fork()) == 0) {
    demonio(semid);
  }
  else if ((pCln = fork()) == 0) {
    cliente(semid);
  }
  else {
    int status; 
    waitpid(pDem, &status, 0);
    waitpid(pCln, &status, 0);
  }
 
  semctl(semid, 0, IPC_RMID); 
 
  return EXIT_SUCCESS;
}
 
void demonio(int semid) {
  for (;;) {
    struct sembuf ops[1]; //  = { { 0, -1, 0} };
 
    // wait(sem)
    ops[0].sem_num = 0;
    ops[0].sem_op  = -1;
    ops[0].sem_flg = 0;
    cout << "Esperando por mensajes de impresion" << endl;
    semop(semid, ops, 1);
    cout << "Operacion recibida" << endl;
  }
 
}
 
void cliente(int semid) {
  for (;;) {
    struct sembuf ops[1]; //  = { { 0, -1, 0} };
 
    sleep(10);
    ops[0].sem_num = 0;
    ops[0].sem_op  = 1;
    ops[0].sem_flg = 0;
    cout << "Enviando evento" << endl;
    semop(semid, ops, 1);
  }
 
}

Comments