使用ProcessSerialNumber获取NSRunningApplication

cho*_*rry 7 applescript objective-c nsrunningapplication

我有一个AppleEventDescriptor地方需要获取发送应用程序的包标识符.Apple Event包含一个typeProcessSerialNumber可以被强制转换为ProcessSerialNumber.

问题是GetProcessPID()在10.9 中被弃用了,并且似乎没有得到制裁pid_t可以用来实例化NSRunningApplication使用的方法-runningApplicationWithProcessIdentifier:.

我发现的所有其他选项都存在于Processes.h中,也不推荐使用.

我是否遗漏了某些内容,或者我是否必须遵守此弃用警告?

cho*_*rry 7

布莱恩和丹尼尔提供了很好的线索,帮助我找到了正确的答案,但他们建议的东西只是有点偏.这是我最终解决问题的方法.

Brian对于为进程ID而不是序列号获取Apple事件描述符的代码是正确的:

// get the process id for the application that sent the current Apple Event
NSAppleEventDescriptor *appleEventDescriptor = [[NSAppleEventManager sharedAppleEventManager] currentAppleEvent];
NSAppleEventDescriptor* processSerialDescriptor = [appleEventDescriptor attributeDescriptorForKeyword:keyAddressAttr];
NSAppleEventDescriptor* pidDescriptor = [processSerialDescriptor coerceToDescriptorType:typeKernelProcessID];
Run Code Online (Sandbox Code Playgroud)

问题是,如果你把-int32Value从描述,0值将返回我不知道为什么发生这种情况(即没有进程id):从理论上讲,无论是pid_tSInt32有符号整数.

相反,您需要获取字节值(存储小端)并将它们转换为进程ID:

pid_t pid = *(pid_t *)[[pidDescriptor data] bytes];
Run Code Online (Sandbox Code Playgroud)

从那时起,获取有关正在运行的进程的信息非常简单:

NSRunningApplication *runningApplication = [NSRunningApplication runningApplicationWithProcessIdentifier:pid];
NSString *bundleIdentifer = [runningApplication bundleIdentifier];
Run Code Online (Sandbox Code Playgroud)

此外,丹尼尔的使用建议keySenderPIDAttr在许多情况下都不起作用.在我们新的沙盒世界中,存储在那里的值可能是进程ID /usr/libexec/lsboxd,也称为启动服务沙箱守护程序,而不是发起事件的应用程序的进程ID.

再次感谢Brian和Daniel提供的解决方案帮助!