【问题标题】:sem_open() on macOS success on command line, fail on ApplicationmacOS 上的 sem_open() 在命令行上成功,在应用程序上失败
【发布时间】:2021-04-23 19:12:12
【问题描述】:

sem_open() posix 函数在 macOS 命令行测试代码上成功,但在 macOS 应用测试代码上失败。它返回 0xffff.... 和 errno=1(EPERM) 或 17(EEXIST)。 我在命令行和应用程序上运行与附加相同的代码。 我使用 Xcode 生成的功能设置和 Info.plist。

命令行代码:有效

//  main.m
#import <Foundation/Foundation.h>
#include <semaphore.h>
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        sem_unlink("pSem");
        errno = 0;
        sem_t *sem = sem_open ("pSem", O_CREAT | O_EXCL, 0777, 1);
        fprintf (stderr, "sem=%p errno=%d\n\n", sem, errno); // sem=0x03 errno=0
    }
    return 0;
}

应用代码的ViewController.m:失败

#import "ViewController.h"
#include <semaphore.h>
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    sem_unlink("pSem2");
    errno = 0;
    sem_t *sem = sem_open ("pSem2", O_CREAT | O_EXCL, 0777, 1);
    fprintf (stderr, "sem=%p errno=%d\n\n", sem, errno); //sem=0xff...ff errno=1 or 17 
}
@end

我使用 macOS Big Sur 11.2.3、Xcode 12.4

【问题讨论】:

  • 如果我更改 myapp.entitlements App Sandbox=NO,此代码有效。
  • 我使用 dispatch_semaphore_create() 并且它与 Sandbox=YES 一起使用

标签: multithreading macos semaphore


【解决方案1】:

在您的失败案例的更大环境中有些不同。

sem_open 失败时,它会返回 SEM_FAILED — 这可能是您系统上的 (sem_t *)-1errno 值会告诉您出了什么问题:

EEXIST - 指定的信号量已经存在,但您要求专门 (O_EXCL) 创建 (O_CREAT) 该名称的新信号量。

EPERM - 您的进程缺少打开信号量的权限。

我可以找到的 OS X 手册页中没有记录后一个错误代码,但是当所有者权限干扰操作时,某些 (BSD) 系统会设置该错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-18
    • 2021-09-24
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    相关资源
    最近更新 更多