objective-c – NSTask NSPipe – objective c命令行帮助

前端之家收集整理的这篇文章主要介绍了objective-c – NSTask NSPipe – objective c命令行帮助前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我的代码
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).

最终代码建议:

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.
原文链接:https://www.f2er.com/c/111948.html

猜你在找的C&C++相关文章