How to run a shell command from my Cocoa application?

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

+3
source share
4 answers

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;
}
+4
source

NSTask - , . script , STPrivilegedTask.

0

Source: https://habr.com/ru/post/1724439/


All Articles