13.2. Running Scripts with Cocoa

Cocoa provides a number of classes that can be used to help run subprocesses and communicate with them. The most important of these classes is NSTask, which allows you to run scripts and other executables, and provides fine control over program arguments, environment variables, and access to standard input and output. NSTask runs subprocesses asynchronously, but provides a method for waiting until the subprocess completes, which is equivalent to running the subprocess synchronously. NSTask also provides methods for suspending, resuming, and terminating a subprocess. In short, NSTask gives you much more control over external scripts than the C system function.

13.2.1. Introducing NSTask

In its simplest form, NSTask can be almost as easy to use as system. Take this example of using a script to list the contents of two directories:

#import <Foundation/Foundation.h>
int main() {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSArray *args = [NSArray arrayWithObjects:@"/bin", @"/sbin", nil];
    NSTask *task = [NSTask launchedTaskWithLaunchPath:@"./list.sh" arguments:args];
    [task waitUntilExit];
    int exitStatus = [task terminationStatus];

    [pool release];
    return exitStatus;
}

This program creates an NSTask with the convenience constructor launchedTaskWithLaunchPath:arguments:. The launch path of an NSTask is the path to the script or other executable that will be run. The arguments are passed to the script when it is run. They are equivalent ...

Get Beginning Mac OS® X Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.