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

时间:2012-05-17 16:12:28

标签: objective-c shell command nstask nspipe

这是我的代码。当我设置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);

1 个答案:

答案 0 :(得分:1)

  

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

它与m ls -l的不同之处在于它不会写任何输出。您的计划可能会在致电-availableData时被屏蔽。


不幸的是,我没有时间尝试任何想法,但这里有一些你可能会尝试的事情。

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

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

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

顺便说一句,我应该指出,将cd发送到shell是你做的最后一件事,这是一个毫无意义的操作。接下来发生的事情是shell退出并且cd结果丢失。如果您的目标是更改当前流程中的目录,请查看 [NSFilemanager changeCurrentDirectoryPath:]