views:

253

answers:

3

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

+7  A: 

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

Dave DeLong
Thanks a bunch!!
Matt S.
thats very stange hmmm...
streetparade
+3  A: 

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;
}
streetparade
+1  A: 

the answer streetparade gave will not work most of the time, refer to this article

http://www.cocoadev.com/index.pl?NSTaskArguments

Madcapslaugh
That doesn't directly address streetparade's answer. What's wrong with the answer (aside from the general folly of using the shell to run commands instead of just running them yourself)?
Peter Hosey