我在Mac編程方面很新穎。我正在向OSX移植一個插件。我需要我的應用程序啓動第二個應用程序(我不控制源代碼),然後獲取退出代碼。 NSWorkspace launchApplicationAtURL非常適合用所需的參數啓動它,但我無法看到如何獲取退出代碼。在設置終止第二個應用程序的通知後有沒有辦法獲得它?我看到了使用NSTask代替退出代碼的工具。我應該使用它嗎?使用NSWorkspace啓動應用程序後退出狀態launchApplicationAtURL
3
A
回答
6
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線程,供應標準輸入等
1
事實上,NSTask的這個屬性應該做的伎倆:terminationStatus
從蘋果的doc:
返回接收器的可執行文件返回的退出狀態。
- (INT)terminationStatus
我測試,它工作正常。注意測試任務是否先運行,否則將啓動異常。
if (![aTask isRunning]) {
int status = [aTask terminationStatus];
if (status == ATASK_SUCCESS_VALUE)
NSLog(@"Task succeeded.");
else
NSLog(@"Task failed.");
}
希望它能幫助。
非常感謝!我有一個更加基本的NSTask版本,但這非常有用。我的困惑是NSTask vs NSWorkspace的相對目的。不知何故,我得到了NSWorkspace取代NSTask的印象。 – Ben 2011-03-15 15:11:07
謝謝,最後一行我改回 [[[的NSString頁頭] initWithData:數據編碼:NSUTF8StringEncoding]自動釋放] 因爲應用程序崩潰 – 2017-11-16 14:24:44