문제

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);
}
도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top