问题描述
我是Mac编程的新手.我正在将插件移植到OSX.我需要我的应用程序启动第二个应用程序(我不控制其源代码),然后获取其退出代码.NSWorkspace launchApplicationAtURL非常适合使用所需的参数启动它,但是我看不到如何获取退出代码.设置终止第二个应用程序的通知后,有没有办法得到它?我看到了使用NSTask来获取退出代码的工具.我应该使用那个吗?
I'm kind of new at Mac programming. I am porting a plugin to OSX. I need my application to launch a second app (which I do not control the source for) and then get its exit code. NSWorkspace launchApplicationAtURL works great to launch it with the needed arguments but I can't see how to get the exit code. Is there a way to get it after setting up notification for termination of the second app? I see tools for getting an exit code using NSTask instead. Should I be using that?
推荐答案
NSWorkspace
方法实际上是用于启动独立的应用程序的.根据文档,使用 NSTask
将另一个程序作为子进程运行,并...监视该程序的执行".
The NSWorkspace
methods are really for launching independent applications; use NSTask
to "run another program as a subprocess and ... monitor that program’s execution" as per the docs.
这是启动可执行文件并返回其标准输出的简单方法-它阻止等待完成:
Here is a simple method to launch an executable and return its standard output - it blocks waiting for completion:
// 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线程,提供标准输入等时.
You may not want to block, especially if this is your main UI thread, supply standard input etc.
这篇关于使用NSWorkspace launchApplicationAtURL启动应用程序后获取退出状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!