NSTask NSPipe-目标C命令行帮助 [英] NSTask NSPipe - objective c command line help

查看:133
本文介绍了NSTask NSPipe-目标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];

所以我正在尝试复制它:

So I'm trying to replicate this:

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错误
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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆