2014-11-25 61 views
1

我想叫可可應用UNIX命令,但它不工作,我想叫可可應用UNIX命令,但它不工作,

命令:「LUA -v」

可可代碼:

NSArray *cmdArray = [cmd componentsSeparatedByString:@" "]; 
NSPipe *pipe = [NSPipe pipe]; 
NSFileHandle *file = pipe.fileHandleForReading; 

NSTask *task = [[NSTask alloc] init]; 
[task setStandardOutput:pipe]; 
task.launchPath = cmdArray[0]; 
if(cmdArray.count > 1) 
{ 
    task.arguments = [cmdArray subarrayWithRange:NSMakeRange(1, cmdArray.count - 1)]; 
} 
[task launch] ; 
NSData *data = [file readDataToEndOfFile]; 
[file closeFile] ; 

NSString *grepOutput = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
return grepOutput; 

的數據始終是0字節

回答

0

NSTask不運行Unix的「命令」,而它運行在Unix「過程」,而不同的是至關重要的。

當您的代碼在Xcode中運行時,您應該在控制檯窗口中看到「啓動路徑不可訪問」,這是您遇到問題的線索。 launch的文檔告訴您,如果啓動路徑無效,則會引發異常。

當您在Unix命令提示符下鍵入時,例如「echo Hello」,您正在將數據輸入到命令解釋程序「shell」中。 shell必須定位應用程序「echo」才能啓動運行它的進程。 shell通過搜索PATH環境變量指定的一組目錄來執行此操作,在「echo」的情況下找到「/ bin/echo」。這是你必須設置launchPath屬性的路徑。

如果你想使用NSTask爲此,你有兩個基本的選擇(一)有你的代碼找到「LUA」二進制文件本身或(b)使用NSTask運行shell和有殼做正常的處理您。

標準的「sh」shell位於「/ bin/sh」。如果你閱讀它的手冊頁,你會看到它需要一個選項「-c 字符串」,它指示它將字符串作爲命令輸入。 E.g考慮以下終端成績單:

crd$ echo Hello 
Hello 
crd$ sh -c "echo Hello" 
Hello 
crd$ 

在第一種情況下,殼發現「回聲」的二進制,並且通過它的「Hello」執行。在第二個中,它找到了「sh」的二進制文件,並執行了傳遞它的「-c」和「echo Hello」,該進程又找到了「echo」的二進制文件。

所以使用NSTask你可以調用「/ bin/sh」並將其作爲參數「-c」和你的命令行傳遞,然後shell會像終端一樣解析你的命令行並調用你的命令,的行:

NSPipe *pipe = [NSPipe pipe]; 
NSFileHandle *file = pipe.fileHandleForReading; 

NSTask *task = [[NSTask alloc] init]; 
task.standardOutput = pipe; 
task.standardError =pipe; // capture any error messages the sh writes, could send to another pipe 
task.launchPath = @"/bin/sh"; 
task.arguments = @[@"-c", cmd]; 

[task launch]; 
NSData *data = [file readDataToEndOfFile]; 
[file closeFile]; 

HTH

相關問題