I am trying to create a small rsync program in Cbjective-C. It presently accesses the terminal command line through an NSTask and reads the command line's output to a string that is displayed in a NSTextField; however, when I use this small program on a very large file (around 8 gb) it does not display the output until after the RSYNC is complete. I want the NSTextField to continually update while the process is running. I have the following code and am looking for ideas!:
-(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);
}
}
OK, the issue is with the way in which you are reading the data from the pipe. You are using:
NSData *data = [file readDataToEndOfFile];
Which will read everything written by the child process in one go, up until the pipe closes (when the child process has terminated).
What you need to do is read a character at-at-time and reconstruct the output line. You also want to use non-blocking mode, so that your main UI thread isn't interrupted when there is no data to read (better still, this should be done in a background thread so that the main UI thread remains completely uninterrupted).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.