简体   繁体   中英

sem_wait POSIX API and OSX

Im trying to write a simple semaphore program, and found out several things that are different in OSX. I use Mountain Lion and the latest Xcode version. Forgetting the syntactical errors, of missing braces.. because i have more code below, did not copy the full snippet,

Basically i except the code to stop with the sem_wait and not go beyond.

the code compiles and output is as follows

Output:
-------
    Semaphore wait failed with ret code: -1, and err: 9. 
    Semaphore init failed with ret code: -1, and err: 9.

Tracing back to error code 9, it is EBADF

My program is

int main(int argc, char * argv[])
{
    pthread_t tid1, tid2;
    int rc;

    rc = sem_unlink(&mutex);
    rc = sem_open(&mutex, O_CREAT,O_RDWR,0);
    rc = sem_wait(&mutex);

    if(rc == 0) {
        printf("Semaphore try wait ok!. \n");
    } else {
        printf("Semaphore wait failed with ret code: %d, and err: %d. \n",
               rc, errno);
    }

    if(rc != SEM_FAILED) {
        printf("Semaphore init ok!. \n");
    } else {
        printf("Semaphore init failed with ret code: %d, and err: %d. \n",
               rc, errno);
        return 0;
    }

Any help here is highly invaluable.

sem_unlink takes a char * that is the name of the semaphore. sem_open takes the same, and returns a semaphore descriptor of type sem_t * . It's this semaphore descriptor that you should be passing to sem_wait . If you fix things so it actually compiles without warnings, like the code below, then it behaves as you'd expect:

#include <semaphore.h>
#include <stdio.h>
#include <sys/errno.h>


int main(int argc, char **argv)
{
    const char *semaphore_name = "my-test-semaphore";

    int rc = sem_unlink(semaphore_name);
    if (rc)
        perror("sem_unlink");

    sem_t *semaphore = sem_open(semaphore_name, O_CREAT, O_RDWR, 0);
    if (semaphore == SEM_FAILED) {
        perror("sem_open");
        return 1;
    }

    rc = sem_wait(semaphore);
    if (rc) {
        perror("sem_wait");
        return 1;
    }

    return 0;
}

You should also be aware of the problems with POSIX semaphores , namely that it's very easy to leak the semaphore count if your application exits unexpectedly. The fact that your sample code mentioned pthread_t suggests that you're trying to use semaphores within a single process. Named POSIX semaphores are not what you want for that task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM