OS X上的奇怪/不正确的sem_getvalue信号量行为

时间:2009-05-16 01:29:57

标签: c++ macos posix mutex semaphore

我有一些非常基本的信号量代码在Linux上运行良好,但在我的生活中不能让它在OS X上正常运行...它返回最奇怪的结果......

#include <iostream>
#include <fcntl.h>
#include <stdio.h>
#include <semaphore.h>

int main()
{
    sem_t* test;
    test = sem_open("test", O_CREAT, 0, 1);

    int value;
    sem_getvalue(test, &value);
    printf("Semaphore initialized to %d\n", value);
}

使用g ++在OS X上进行编译会返回以下输出:

iQudsi:Desktop mqudsi$ g++ test.cpp
iQudsi:Desktop mqudsi$ ./a.out 
Semaphore initialized to -1881139893

而在Ubuntu上,我得到了明显更加明智的结果:

iQudsi: Desktop mqudsi$ g++ test.cpp -lrt
iQudsi:Desktop mqudsi$ ./a.out 
Semaphore initialized to 1

我已经连续工作了3个小时,并且无法弄清楚为什么OS X会返回如此奇怪的结果......

我尝试使用文件路径作为信号量名称,它没有什么区别。

我很感激我能得到的任何帮助。

3 个答案:

答案 0 :(得分:8)

您是否在测试错误?尝试:

#include <iostream>
#include <fcntl.h>
#include <stdio.h>
#include <semaphore.h>

int main()
{
    sem_t* test;
    test = sem_open("test", O_CREAT, 0, 1);
    if (test == SEM_FAILED) {
        perror("sem_open");
        return 1;
    }

    int value;
    if (sem_getvalue(test, &value)) {
        perror("sem_getvalue");
        return 1;
    }
    printf("Semaphore initialized to %d\n", value);
}

答案 1 :(得分:6)

$ g++ sem-testing.cc -Wall
$ ./a.out 
sem_getvalue: Function not implemented
$ man sem_getvalue
No manual entry for sem_getvalue

您正在使用当前未在Mac OS X中实现的功能,并且您要打印的整数包含初始化整数的默认数据,该数据可能是仍在内存中的随机数据。如果你把它归零,通过设置int value = 0;,你可能很快就会发现这个错误。

这是我使用的代码(感谢bdonlan):

#include <iostream>
#include <fcntl.h>
#include <stdio.h>
#include <semaphore.h>

int main()
{
    sem_t* test;
    test = sem_open("test", O_CREAT, 0, 1);
    if (test == SEM_FAILED) {
        perror("sem_open");
        return 1;
    }

    int value;
    if (sem_getvalue(test, &value)) {
        perror("sem_getvalue");
        return 1;
    }
    printf("Semaphore initialized to %d\n", value);
}

答案 2 :(得分:2)

好吧,也许sem_open()失败了 - 你没有测试过。

或者,也许OSX不默认支持共享posix sems - 如果没有挂载/ dev / shm,通常系统不支持sem_open()。

您可能想要使用SysV信号量。

有关Slackware的类似问题在这里被问到:how-do-i-stop-semopen-failing-with-enosys

然而,进一步的搜索显示OSX名为semaphones是建立在Mach信号量之上的,当你完成时你可能需要sem_unlink()它们(不仅仅是sem_close(),或者可能代替),你应该小心关于权限 - 我建议从0777或0700开始,而不是0。请参阅posiz semaphores in Darwin

相关问题