C semaphores: sem_wait throwing inexplicable error

前端 未结 1 1003
别那么骄傲
别那么骄傲 2021-01-24 02:48

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

1条回答
  •  梦毁少年i
    2021-01-24 03:21

    Keep in mind that the Single UNIX Spec may not necessarily be the controlling document in your case. Granted, it probably should be, but since you haven't actually specified the platform, it may be that you're in an environment that decided to follow different rules and/or have other return codes.

    A couple of things to check.

    1/ Are you sure that sem_wait is returning -1? I've seen coders simply check errno following a call, not realising that most calls don't set it to zero on success, rather they simply leave it alone. It's possible that such a situation would arise if errno were set to EBADF before the sem_wait call.

    2/ Have you followed all the rules in creating the semaphores, such as initialising them?

    3/ Are you referring to a valid semaphore? Primarily, are you certain that the me index is not out of range?

    Short of seeing some code, that's about all the advice I have to give.


    One thing I found with a cursory google of sem_wait ebadf is here. Turns out this was a problem with using errno in a threaded environment without including the correct headers.

    By doing that, the global errno value was being used rather than the correct threaded macro (which would give the thread-specific errno).

    Whether that's your problem, I have no idea, but it may be worth looking into.


    And following that chain of messages a little more closely, there are some other possibilities.

    4/ Are you using sem_init to initialise the semaphores. If so, check its return value. The messages are from 2008 so it may be dated information, but OSX may still not support sem_init, preferring sem_open (see here). You really should check the return codes from all your sem_ functions as well, just to be certain (if you're using sem_init for them all (and if it's unsupported) and are only checking one, you may find that they're all failing).

    5/ There is (was?) a race condition in the thread errno function chain under OSX where the __error function called another library call pthread_self before using errno (in main thread, or current_thread->errno in other threads). Technically this is not allowed and there was a small window where problems could occur.

    0 讨论(0)
提交回复
热议问题