Add a timeout to NSTask

February 18, 2011 by · Leave a Comment 

// 1 minute timeout
NSDate *terminateDate = [[NSDate date] addTimeInterval:60.0];
while ((theTask != nil) && ([theTask isRunning]))	{
	if ([[NSDate date] compare:(id)terminateDate] == NSOrderedDescending)	{
		NSLog(@"Error: terminating task, timeout was reached.");
		[theTask terminate];
	[NSThread sleepForTimeInterval:1.0];

NSTask without worrying about the output buffer

February 18, 2011 by · 1 Comment 

Some times you might want to run NSTask without setting up a delegate for when data becomes available or to notify once the task has terminated because it in a procedural part of your application.

Here is a quick example using system_profiler and Applications…

NSTask *task = [[[NSTask alloc] init] autorelease];
[task setLaunchPath:@"/usr/sbin/system_profiler"];
[task setArguments:[NSArray arrayWithObjects:@"SPApplicationsDataType",nil]];

NSPipe *l_Pipe = [NSPipe pipe];
NSFileHandle *readHandle = [l_Pipe fileHandleForReading];

[task setStandardOutput:l_Pipe];
[task setStandardError:l_Pipe];
[task launch];

NSMutableData *data = [[NSMutableData alloc] init];
NSData *readData;
while ((readData = [readHandle availableData]) && [readData length]) {
    [data appendData: readData];
// We now have our full results in a NSString
NSString *spStringData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

[spStringData release];
[data release];
[task release];