PDA

View Full Version : NSTask Question


ast3r3x
2009-05-11, 23:00
So I'm playing with NSTask and trying to get it to work and I'm confused about what is happening. In processOutput it says [data length] is 0, although if I run "git diff" from the terminal in "/Users/dustins/Sites" then I get the output I'd expect. Shouldn't they be the same thing, what am I missing?

- (void)processOutput:(NSNotification *)aNotification {
NSFileHandle *readHandle = [aTask standardOutput];
NSData *data = [readHandle availableData];

NSLog(@"%d \n", [data length]);

[aTask release]; // Don't forget to clean up memory
aTask = nil; // Just in case...
}

- (IBAction)getDiff:(id)sender
{
aTask = [[NSTask alloc] init];
NSMutableArray *args = [NSMutableArray array];
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *readHandle = [pipe fileHandleForReading];

/* set arguments */
[args addObject:@"diff"];

[aTask setLaunchPath:@"/usr/local/git/bin/git"];
[aTask setCurrentDirectoryPath:@"/Users/dustins/Sites"];
[aTask setArguments:args];
[aTask setStandardOutput:readHandle];
[aTask launch];
}

RobUSVI
2009-05-12, 08:24
Try adding:

[aTask waitUntilExit];

int status = [aTask terminationStatus];
if (status == ATASK_SUCCESS_VALUE)
NSLog(@"Task succeeded.");
else
NSLog(@"Task failed: status=%d.", status);

... after you launch the task.

ast3r3x
2009-05-12, 20:48
Ummm…it works now? It no longer hangs up, even if I don't add the waitUntilExit. Not sure what the deal is, but I'm happy.

Now my next question…I'm getting output from git…is really the best option to just parse the output with regular expressions or something to get the information I want? That seems like such a hack haha.

Edit: Oh, I think it was because I was setting the output to the readhandle and not the pipe.

ShadowOfGed
2009-05-12, 22:29
So I'm playing with NSTask and trying to get it to work and I'm confused about what is happening. In processOutput it says [data length] is 0, although if I run "git diff" from the terminal in "/Users/dustins/Sites" then I get the output I'd expect. Shouldn't they be the same thing, what am I missing?

This shouldn't work at all. You're giving the read end of a pipe to a process that expects said file handle to be writable.

Here is what needs to change:


- (void) processOutput:(NSNotification *)aNotification {
NSFileHandle *readHandle = [[aTask standardOutput] fileHandleForReading];
/* … */
}

- (IBAction) getDiff:(id)sender {
/* … */
[aTask setStandardOutput:pipe];
/* … */
}


NSTask will handle the pipe for you, handing the task the write end and closing it in your process after it's launched. You then want to extract the read end for your purposes later.