jfcmacro

Fumador.cpp

Mar 22nd, 2019
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1. #include <fcntl.h>           /* For O_* constants */
  2. #include <sys/stat.h>        /* For mode constants */
  3. #include <semaphore.h>
  4. #include <iostream>
  5. #include <cstdlib>
  6. #include <cstring>
  7. #include <cerrno>
  8. #include <unistd.h>
  9.  
  10. using namespace std;
  11.  
  12. static void usage(const char*);
  13. static void fumador(const char *,
  14.             sem_t *,
  15.             sem_t *);
  16.  
  17. int
  18. main(int argc, char *argv[]) {
  19.  
  20.   if (argc != 3) usage(argv[0]);
  21.  
  22.   sem_t *espera = sem_open(argv[1], 0);
  23.  
  24.   if (espera == nullptr) {
  25.     cerr << "Error abriendo " << argv[1]
  26.      << " semaforo: "
  27.      << strerror(errno) << endl;
  28.   }
  29.  
  30.   sem_t *esperaagente = sem_open(argv[2], 0);
  31.  
  32.   if (espera == nullptr) {
  33.     cerr << "Error abriendo " << argv[1]
  34.      << " semaforo: "
  35.      << strerror(errno) << endl;
  36.   }
  37.  
  38.   fumador(argv[1], espera, esperaagente);
  39.  
  40.   return EXIT_SUCCESS;
  41. }
  42.  
  43. static void usage(const char* progname) {
  44.   cerr << "Uso: " << progname
  45.        << " <nombre semaforo> "
  46.        << endl;
  47.   exit(EXIT_FAILURE);
  48. }
  49.  
  50. static void fumador(const char *nombre,
  51.             sem_t *espera,
  52.             sem_t *esperaagente) {
  53.  
  54.   for (;;) {
  55.     sem_wait(espera);
  56.     cerr << "Fumador: " << nombre
  57.      << " fumando" << endl;
  58.     sleep(rand() % 10);
  59.     sem_post(esperaagente);
  60.   }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment