jfcmacro icon

Fumador.cpp

jfcmacro | PRO | 03/22/19 04:52:51 PM UTC | 0 ⭐ | 448 👁️ | Never ⏰ | []
C++ |

1.18 KB

|

None

|

0 👍

/

0 👎

#include <fcntl.h>           /* For O_* constants */
#include <sys/stat.h>        /* For mode constants */
#include <semaphore.h>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <unistd.h>
 
using namespace std;
 
static void usage(const char*);
static void fumador(const char *,
            sem_t *,
            sem_t *);
 
int
main(int argc, char *argv[]) {
 
  if (argc != 3) usage(argv[0]);
 
  sem_t *espera = sem_open(argv[1], 0);
 
  if (espera == nullptr) {
    cerr << "Error abriendo " << argv[1]
     << " semaforo: "
     << strerror(errno) << endl;
  }
  
  sem_t *esperaagente = sem_open(argv[2], 0);
  
  if (espera == nullptr) {
    cerr << "Error abriendo " << argv[1]
     << " semaforo: "
     << strerror(errno) << endl;
  }
 
  fumador(argv[1], espera, esperaagente);
 
  return EXIT_SUCCESS;
}
 
static void usage(const char* progname) {
  cerr << "Uso: " << progname
       << " <nombre semaforo> "
       << endl;
  exit(EXIT_FAILURE);
}
 
static void fumador(const char *nombre,
            sem_t *espera,
            sem_t *esperaagente) {
 
  for (;;) {
    sem_wait(espera);
    cerr << "Fumador: " << nombre
     << " fumando" << endl;
    sleep(rand() % 10);
    sem_post(esperaagente);
  }
}

Comments