繁体   English   中英

使用NSTask执行shell命令时,通过NSPipe输出的奇怪问题

[英]Strange issue of output via NSPipe when execute shell command using NSTask

这是我的代码。 当我设置myCmd=@"cd /\\nls -l\\n"myCmd=@"ls -l\\n" ,这没问题。 但是,当我设置myCmd=@"cd /\\n"if ((output =[[outPipe fileHandleForReading] availableData]) && [output length]) ,程序死在该行中,并且没有调试信息输出。

我不知道"cd /" cmd是否与其他shell命令不同。 你能给我一些建议吗?

NSData *inputData = [myCmd dataUsingEncoding:NSUTF8StringEncoding];
NSPipe *inPipe = [NSPipe pipe];
NSFileHandle *fh = [inPipe fileHandleForWriting];
[fh writeData: inputData];
NSPipe *outPipe = [NSPipe pipe];
//NSPipe *errPipe = [NSPipe pipe];
NSTask *task = [[NSTask alloc] init];
[task setStandardInput:inPipe];
[task setStandardOutput:outPipe];
[task setStandardError:outPipe];
[task setLaunchPath:@"/bin/sh"];
NSArray *args = [NSArray arrayWithObject:@"-s"];
[task setArguments:args];

[task launch];

NSData *output;
NSString *string;

if ((output =[[outPipe fileHandleForReading] availableData]) && [output length]) 
{
    string = [[NSString alloc] initWithFormat:@"%.s", [output bytes]];
}
NSLog(@"%@", string);

我不知道cd / cmd是否与其他shell命令不同。

它与m ls -l的不同之处在于它不写入任何输出。 您的程序可能在-availableData调用中被阻止。


不幸的是,我没有时间尝试任何想法,但是您可以尝试以下一些方法。

  • 您可以尝试启动任务,然后将数据发送到输入管道,然后关闭输入管道。 当任务看到输入结束时,它将关闭输出管道,这意味着您对-availableData的调用将以文件结尾返回。

  • 您可以使用运行循环异步读取输出。 这样做更加灵活,因为您不必一次发送所有命令。 完成后,您仍然需要关闭输入。

  • 您可以在NSOperation中读取输出,这可以有效地将其放在其他线程上。 同样,完成后,您仍然需要关闭输入管道。

顺便说一句,我应该指出,将cd作为最后一步发送到shell是没有意义的操作。 接下来发生的事情是外壳退出并且cd结果丢失。 如果您的目标是在当前进程中更改目录,请查看[NSFilemanager changeCurrentDirectoryPath:]。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM