NSTask NSPipe - 目标 c 命令行帮助 [英] NSTask NSPipe - objective c command line help
问题描述
这是我的代码:
task = [[NSTask alloc] init];
[task setCurrentDirectoryPath:@"/applications/jarvis/brain/"];
[task setLaunchPath:@"/applications/jarvis/brain/server.sh"];
NSPipe * out = [NSPipe pipe];
[task setStandardOutput:out];
[task launch];
[task waitUntilExit];
[task release];
NSFileHandle * read = [out fileHandleForReading];
NSData * dataRead = [read readDataToEndOfFile];
NSString * stringRead = [[[NSString alloc] initWithData:dataRead encoding:NSUTF8StringEncoding] autorelease];
所以我试图复制这个:
cd /applications/jarvis/brain/
./server.sh
但是在objective-c中使用NSTask.
but using NSTask in objective-c.
但出于某种原因,当我运行此代码时,stringRead 不返回任何内容.当我启动 .sh 文件时,它应该返回终端返回的内容.正确吗?
For some reason though, when I run this code, stringRead, returns nothing. It should return what terminal is returning when I launch the .sh file. Correct?
有什么想法吗?
以利亚
推荐答案
Xcode Bug
在启动使用标准输出的新任务后,Xcode 中有一个错误会阻止它打印任何输出(它收集所有输出,但不再打印任何内容).您将不得不调用 [task setStandardInput:[NSPipe pipe]]
以使其再次显示输出(或者,将任务打印到 stderr 而不是 stdout).
Xcode Bug
There's a bug in Xcode that stops it from printing any output after a a new task using standard output is launched (it collects all output, but no longer prints anything). You're going to have to call [task setStandardInput:[NSPipe pipe]]
to get it to show output again (or, alternatively, have the task print to stderr instead of stdout).
对最终代码的建议:
NSTask *server = [NSTask new];
[server setLaunchPath:@"/bin/sh"];
[server setArguments:[NSArray arrayWithObject:@"/path/to/server.sh"]];
[server setCurrentDirectoryPath:@"/path/to/current/directory/"];
NSPipe *outputPipe = [NSPipe pipe];
[server setStandardInput:[NSPipe pipe]];
[server setStandardOutput:outputPipe];
[server launch];
[server waitUntilExit]; // Alternatively, make it asynchronous.
[server release];
NSData *outputData = [[outputPipe fileHandleForReading] readDataToEndOfFile];
NSString *outputString = [[[NSString alloc] initWithData:outputData encoding:NSUTF8StringEncoding] autorelease]; // Autorelease optional, depending on usage.
这篇关于NSTask NSPipe - 目标 c 命令行帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!