![](/img/trans.png)
[英]NSTask and NSPipe example to comunicate with the command line objective-c
[英]Objective-c: How to use NSPipe output the illegal command echo in a NSTask?
我有類似下面的代碼,沒關系,但是我有2個問題。
1)如果我為sh分配了一些非法參數,例如@“ ls-l”,則outString為null。 也就是說,它無法捕獲錯誤警告“ ls:-:沒有這樣的文件或目錄ls:l:沒有這樣的文件或目錄”。 我該如何處理?
2)如何實現此功能:給定應用程序的當前目錄為“ / user / Doc” ,然后執行sh = @“ cd /” ,然后執行sh = @“ ls -l”來查看內容下一個循環中的“ /”目錄。 但是,當新循環開始時,當前目錄將恢復為“ / user / Doc”。 如何保持上一個循環的任務環境?
此外,就像直接在Terminal上進行工作一樣,我可以繼續執行“ / bin / sh”嗎?
NSString *sh = @"ls -l";
while(sh != @"end"){
NSTask *shData = [[NSTask alloc] init];
[shData setLaunchPath: @"/bin/sh"];
NSArray *args;
args = [NSArray arrayWithObjects: @"-c", sh, nil];
[shData setArguments: args];
NSPipe *myPipe;
myPipe = [NSPipe pipe];
[shData setStandardOutput: myPipe];
[shData setStandardInput:[NSPipe pipe]];
NSFileHandle *file;
file = [myPipe fileHandleForReading];
[shData launch];
NSData *data1;
data1 = [file readDataToEndOfFile];
NSString *outString;
outString = [[NSString alloc] initWithData: data1 encoding: NSUTF8StringEncoding];
NSLog(@"%@",outString);
}
該字符串存在標准錯誤,而不是標准輸出。 由於您不檢查錯誤流,因此找不到它。
子外殼不是這樣工作的。 Google提供了“為什么CD是內置CD的外殼”的信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.