I'm working on a problem which we have to use semaphores to solve. I have an array which contains two semaphores, gsem
, and given certain conditions call sem_wait(&(gsem[me]))
, which is supposed to waiting until that particular process is woken up. However, for some reason it gives me the error Bad file descriptor
. I looked up sem_wait
and the Open Group spec says this is not an error sem_wait
can cause. This is making my whole program crazy and I have no idea why this is failing.
EDIT: Offending code, as requested.
120 sem_wait(&mutex);
121 if (inside[opp] > 0 || waiting[opp] > 0) {
122 sem_wait(&screen);
123 printf("%s %u waiting\n", names[me], t);
124 sem_post(&screen);
125 waiting[me]++;
126 sem_post(&mutex);
127 int hg = sem_wait(&(gsem[me]));
128 if (hg < 0)
129 printf("%s\n", strerror(errno));
130 }
I should note this is a homework assignment for which we are required to use semaphores. The professor calls it the "unisex bathroom". Either men and women can use it, but not simultaneously. inside[opp]
is the number of people of the opposite sex in the bathroom. waiting[opp]
is the number of the opposite sex waiting to use it. screen
is a semaphore which locks access to stdout
. The solution is based on a solution to the readers/writers problem given in our textbook which uses passing the baton.
I should also note that we first had to code a solution in Ada and then convert it to C. My Ada solution works, and I translated it verbatim. I'm sure it's some minor syntactical detail. Lastly, I'm working on Snow Leopard, if that helps.