我是 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/