gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:25:07 32 4
gpt4 key购买 nike

这是我的代码:

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。

但出于某种原因,当我运行这段代码时,stringRead 没有返回任何内容。当我启动 .sh 文件时,它应该返回终端正在返回的内容。正确吗?

有什么想法吗?

以利亚

最佳答案

Xcode 错误
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.

关于objective-c - NSTask NSPipe - objective c 命令行帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3444178/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com