我正在尝试用Cbjective-C创建一个小的rsync程序。它目前通过NSTask访问终端命令行,并将命令行的输出读取为在NSTextField中显示的字符串;但是,当我在一个非常大的文件(大约8 gb)上使用这个小程序时,它直到RSYNC完成后才显示输出。我希望NSTextField在进程运行时不断更新。我有以下代码,正在寻找想法!
-(IBAction)sync:(id)sender
{
NSString *sourcePath = self.source.stringValue;
NSString *destinationPath = self.destination.stringValue;
NSLog(@"The source is %@. The destination is %@.", sourcePath, destinationPath);
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/bin/rsync"];
NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"-rptWav", @"--progress", sourcePath, destinationPath, nil];
[task setArguments: arguments];
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
// [task setStandardInput:[NSPipe pipe]];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
NSData *data;
data = [file readDataToEndOfFile];
while ([task isRunning])
{
NSString *readString;
readString = [[NSString alloc] initWithData: data encoding:NSUTF8StringEncoding];
textView.string = readString;
NSLog(@"grep returned:\n%@", readString);
}
}发布于 2012-10-16 14:58:31
好吧,问题出在你从管道中读取数据的方式上。您正在使用:
NSData *data = [file readDataToEndOfFile];它将一次性读取子进程写入的所有内容,直到管道关闭(当子进程终止时)。
您需要做的是一次读取一个字符并重新构造输出行。您还希望使用非阻塞模式,这样当没有数据可读时,主UI线程就不会中断(更好的做法是,这应该在后台线程中完成,这样主UI线程就完全不会中断)。
https://stackoverflow.com/questions/12829787
复制相似问题