The program sometimes hangs when I try to read from stdin.
I'm not fully familiar with the code, but I think the problem is that this sem_wait gets called multiple times because it's in a loop, but the semaphore only gets unlocked once. (In a particular run, that sem_wait was called two times but, this sem_poll only got called once.)