Home | History | Annotate | Download | only in tests
      1 #include <iostream>
      2 #include <cerrno>
      3 #include <cstring>
      4 #include <pthread.h>
      5 #include <semaphore.h>
      6 
      7 struct FailedOn
      8 {
      9   FailedOn(const char *f, int e) : func(f), eno(e) {}
     10   std::string func;
     11   int eno;
     12 };
     13 
     14 int main(void)
     15 {
     16   try {
     17     sem_t mySemaphore;
     18     if (sem_init(&mySemaphore, 0, 0) != 0)
     19       throw FailedOn("sem_init", errno);
     20 
     21     std::cerr << "Calling sem_trywait\n";
     22     if (sem_trywait(&mySemaphore) != 0) {
     23       if (errno != EAGAIN)
     24         throw FailedOn("sem_trywait", errno);
     25 
     26       std::cerr << "Wait would have blocked" << std::endl;
     27     } else {
     28       std::cerr << "Wait succeeded" << std::endl;
     29     }
     30 
     31     if (sem_destroy(&mySemaphore) != 0)
     32       throw FailedOn("sem_destroy", errno);
     33 
     34     return 0;
     35   } catch (FailedOn &e) {
     36     std::cerr << e.func << " failed: " << strerror(e.eno) << std::endl;
     37   } catch (...) {
     38     std::cerr << "Unknown exception" << std::endl;
     39   }
     40 
     41   return -1;
     42 }
     43