Matt S.
Matt S.

Reputation: 13753

How can I run a shell command from my Cocoa app?

I want to run a simple command from my Cocoa app through code, NOT creating a shell script and running it that way, but by running it through the application, being able to define everything and change it on the fly.

Upvotes: 3

Views: 4093

Answers (2)

streetparade
streetparade

Reputation: 32888

The Function

 void runSystemCommand(NSString *cmd)
    {
        [[NSTask launchedTaskWithLaunchPath:@"/bin/sh"
            arguments:[NSArray arrayWithObjects:@"-c", cmd, nil]]
            waitUntilExit];
    }

usage example:

#import <Foundation/Foundation.h>

void runSystemCommand(NSString *cmd)
{
    [[NSTask launchedTaskWithLaunchPath:@"/bin/sh"
        arguments:[NSArray arrayWithObjects:@"-c", cmd, nil]]
        waitUntilExit];
}

int main(int argc, const char **argv)
{
    NSAutoreleasePool *pool;

    pool = [NSAutoreleasePool new];

    runSystemCommand(@"ls");
    [pool release];
    return 0;
}

Upvotes: 4

Dave DeLong
Dave DeLong

Reputation: 243146

Use an NSTask. http://www.cocoadev.com/index.pl?NSTask

Upvotes: 6

Related Questions