NSTask *task; task = [[NSTask alloc] init]; [task setLaunchPath: @"/bin/ls"]; NSArray *arguments; arguments = [NSArray arrayWithObjects: @"-l", @"-a", @"-t", nil]; [task setArguments: arguments]; NSPipe *pipe; pipe = [NSPipe pipe]; [task setStandardOutput: pipe]; NSFileHandle *file; file = [pipe fileHandleForReading]; [task launch]; NSData *data; data = [file readDataToEndOfFile]; NSString *string; string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog (@"woop! got\n%@", string);Of course, you can use different
NSFileHandle
methods for different styles of reading, and you can make a pipe for standard input so you can feed data to the task.NSTasks
and a bunch of NSPipes
and hook them together, or you can use the "sh -c
" trick to feed a shell a command, and let it parse it and set up all the IPC. This pipeline cats /usr/share/dict/words, finds all the words with 'ham' in them, reverses them, and shows you the last 5.
NSTask *task; task = [[NSTask alloc] init]; [task setLaunchPath: @"/bin/sh"]; NSArray *arguments; arguments = [NSArray arrayWithObjects: @"-c", @"cat /usr/share/dict/words | grep -i ham | rev | tail -5", nil]; [task setArguments: arguments]; // and then do all the other jazz for running an NSTask.One important note:, don't feed in arbitrary user data using this trick, since they could sneak in extra commands you probably don't want to execute.
stripper.pl
which removes everything that looks like an HTML / SGML / XML tag:
Be sure to chmod +x the script. Add it to your project, add a new "Copy Files" phase, and have it stick this script into the Executables directory.#!/usr/bin/perl while (<>) { $_ =~ s/<[^>]*>//gs; print $_; }
This method will take a string and feed it through the perl script:
- (NSString *) stringStrippedOfTags: (NSString *) string { NSBundle *bundle = [NSBundle mainBundle]; NSString *stripperPath; stripperPath = [bundle pathForAuxiliaryExecutable: @"stripper.pl"]; NSTask *task = [[NSTask alloc] init]; [task setLaunchPath: stripperPath]; NSPipe *readPipe = [NSPipe pipe]; NSFileHandle *readHandle = [readPipe fileHandleForReading]; NSPipe *writePipe = [NSPipe pipe]; NSFileHandle *writeHandle = [writePipe fileHandleForWriting]; [task setStandardInput: writePipe]; [task setStandardOutput: readPipe]; [task launch]; [writeHandle writeData: [string dataUsingEncoding: NSASCIIStringEncoding]]; [writeHandle closeFile]; NSMutableData *data = [[NSMutableData alloc] init]; NSData *readData; while ((readData = [readHandle availableData]) && [readData length]) { [data appendData: readData]; } NSString *strippedString; strippedString = [[NSString alloc] initWithData: data encoding: NSASCIIStringEncoding]; [task release]; [data release]; [strippedString autorelease]; return (strippedString); } // stringStrippedOfTags