objective-c - 使用 NSWorkspace launchApplicationAtURL 启动应用程序后获取退出状态

标签 objective-c cocoa macos

我是 Mac 编程的新手。我正在将一个插件移植到 OSX。我需要我的应用程序启动第二个应用程序(我不控制其源代码)然后获取其退出代码。 NSWorkspace launchApplicationAtURL 非常适合使用所需的参数启动它,但我看不到如何获取退出代码。在设置第二个应用程序终止通知后是否有办法获取它?我看到了使用 NSTask 获取退出代码的工具。我应该使用它吗?

最佳答案

NSWorkspace 方法实际上用于启动独立的应用程序;根据文档,使用 NSTask 来“将另一个程序作为子进程运行并......监控该程序的执行”。

这是启动可执行文件并返回其标准输出的简单方法 - 它会阻塞等待完成:

// Arguments:
//    atPath: full pathname of executable
//    arguments: array of arguments to pass, or nil if none
// Return:
//    the standard output, or nil if any error
+ (NSString *) runCommand:(NSString *)atPath withArguments:(NSArray *)arguments
{
    NSTask *task = [NSTask new];
    NSPipe *pipe = [NSPipe new];

    [task setStandardOutput:pipe];     // pipe standard output

    [task setLaunchPath:atPath];       // set path
    if(arguments != nil)
        [task setArguments:arguments]; // set arguments

    [task launch];                     // execute

    NSData *data = [[pipe fileHandleForReading] readDataToEndOfFile]; // read standard output

    [task waitUntilExit];              // wait for completion

    if ([task terminationStatus] != 0) // check termination status
        return nil;

    if (data == nil)
        return nil;

    return [NSString stringWithUTF8Data:data]; // return stdout as string
}

您可能不想阻塞,尤其是当这是您的主 UI 线程、提供标准输入等时。

关于objective-c - 使用 NSWorkspace launchApplicationAtURL 启动应用程序后获取退出状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5302599/

相关文章:

macos - 需要 AVPlayerView 在按下 esc 按钮时退出全屏

macos - DevTools 在 Intellij 中重启两次

python - PyGame 安装 Mac OS X

ios - UITextView 中的动画 Gif

ios - 在 Segue 中但在 ViewDidLoad 中设置属性返回 null

ios - UIView 中的 UIPinchGestureRecognizer 无法正常工作

ios - 从共享 key 生成派生 key (ECDH-ES) - ConcatKDF

objective-c - 在 Objective-C 中通过引用传递数组

python - NSPipe - 如何将返回的数据转换为 NSArray

html - CSS 不会加载它的属性