原文链接:http://rosettacode.org/wiki/Execute_a_System_Command
Objective-C
NSTask runs an external process with explicit path and arguments.
void runls()
{
[[NSTask launchedTaskWithLaunchPath:@"/bin/ls"
arguments:@[]] waitUntilExit];
}
If you need to run a system command, invoke the shell:
void runSystemCommand(NSString *cmd)
{
[[NSTask launchedTaskWithLaunchPath:@"/bin/sh"
arguments:@[@"-c", cmd]]
waitUntilExit];
}
Complete usage example:
#import <Foundation/Foundation.h>
void runSystemCommand(NSString *cmd)
{
[[NSTask launchedTaskWithLaunchPath:@"/bin/sh"
arguments:@[@"-c", cmd]]
waitUntilExit];
}
int main(int argc, const char **argv)
{
@autoreleasepool {
runSystemCommand(@"ls");
}
return 0;
}
Or use the C method above.