这是我的代码:
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
但是在目标c中使用NSTask.
由于某些原因,当我运行这个代码,stringRead,什么都不返回.当我启动.sh文件时,应该返回什么终端返回.正确?
有任何想法吗?
以利亚
解决方法
Xcode Bug
Xcode中存在一个错误,它会在启动了标准输出的新任务之后停止打印任何输出(它收集所有输出,但不再打印任何内容).您将要调用[task setStandardInput:[NSPipe pipe]]来使其再次显示输出(或者,将任务打印到stderr而不是stdout).
Xcode中存在一个错误,它会在启动了标准输出的新任务之后停止打印任何输出(它收集所有输出,但不再打印任何内容).您将要调用[task setStandardInput:[NSPipe pipe]]来使其再次显示输出(或者,将任务打印到stderr而不是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.