Question

I have three POSIX? semaphores and several error conditions. The semaphores are globally accessible. How can I check if they were destroyed before an error occurred (or if they were even initialized in the first place).

// Example c program
#include <semaphore.h>

sem_t mySemaphore;

void errorHandling(){
    // if (mySemaphore exists)
    //     sem_destroy(&mySemaphore);
}

int main(){

    // possible errors

    if ((sem_init(&mySemaphore, 0, 1)) < 0)
        errorHandling();

    // more possible errors and multi threading stuff

    sem_destroy(&mySemaphore);

    return (EXIT_SUCCESS);
}
Was it helpful?

Solution

You need a separate flag which is false by default. Set to true when initialized and back to false when destroyed.

If multi-threaded app, then make sure you mutex protect those accesses. Also, I strongly suggest you write functions to handle all of that in one place.

OTHER TIPS

With reference to OP's code, and according to sem_init() manpage, calling that function on possibly already initialized semaphores results in undefined behavior. If potential races are not your concern, you can try to call sem_getvalue() and use its EINVAL return value to test for prior semphore's initialization.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top