【发布时间】: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