Yet another problem with NSTask and NSPipe

Shawn Erickson shawnce at gmail.com
Tue Apr 24 23:08:59 PDT 2007


On Apr 22, 2007, at 5:17 AM, Dragan Milić wrote:

> Hello all,
>
> I know this topic has been beaten do death during past seven years,  
> yet after reading from archives all that I could find about it and  
> after struggling for couple of days, I'm not able to solve it,  
> hence need some help.
>
> The situation is quite standard. I run hdiutil inside NSTask. The  
> goal is to get information on an image and use it afterwards. For  
> that reason I use -plist option of the hdiutil, so the NSTask  
> should do:
>
> hdiutil imageinfo -plist image_name
>
> Not to spend too many words, here is the part of code that I use:
>
> 	NSPipe *stdInPipe = [NSPipe pipe];
> 	NSPipe *stdOutPipe = [NSPipe pipe];
> 	NSFileHandle *stdOutHandle = [stdOutPipe fileHandleForReading];
> 	[[NSNotificationCenter defaultCenter]
> 			addObserver:self
> 			selector:@selector(outPipeDataAvailable:)
>             name:NSFileHandleReadCompletionNotification
>             object:stdOutHandle];
> 	NSTask *task = [[[NSTask alloc] init] autorelease];
> 	[task setStandardInput:stdInPipe];
> 	[task setStandardOutput:stdOutPipe];
> 	[task setArguments:[NSArray arrayWithObjects:@"hdiutil",  
> @"imageinfo", @"-plist", imageName, nil]];
> 	[task setLaunchPath:@"/usr/bin/env"];
> 	[stdOutHandle readInBackgroundAndNotify];
> 	[self setStdOutData:[NSMutableData data]];
> 	[task launch];
> 	[task waitUntilExit];
> 	int terminationStatus = [task terminationStatus];
> 	[task release];
> 	if (terminationStatus != 0) {
> 		// error handling
> 	}
> 	[[NSNotificationCenter defaultCenter]
> 			removeObserver:self
> 			name:NSFileHandleReadCompletionNotification
> 			object:nil];

Don't use the exit of the task as the trigger to stop reading data.  
Use the ending of the pipe as way to know that you have read all of  
the data.

-Shawn


More information about the MacOSX-dev mailing list