Cocoa/ Objective-C Shell Command Line Execution

2019-01-10 23:25发布

This is probably a stupid question, but how can I execute a shell command from my Cocoa app?

I have the command as a string "command", but can easily manipulate data as needed.

There is no need to get a returned output value.

3条回答
家丑人穷心不美
2楼-- · 2019-01-11 00:01

If you just want to run something and don't care about the output or return code (for example, you want to touch a file), you can just do

system("touch myfile.txt");

Easy as that.

查看更多
三岁会撩人
3楼-- · 2019-01-11 00:09

NSTask is pretty easy to do this with. For a synchronous call, you can use something like this fragment:

NSString *path = @"/path/to/executable";
NSArray *args = [NSArray arrayWithObjects:..., nil];
[[NSTask launchedTaskWithLaunchPath:path arguments:args] waitUntilExit];

The -waitUntilExit call makes sure it finishes before proceeding. If the task can be asynchronous, you can remove that call and just let the NSTask do it's thing.

查看更多
倾城 Initia
4楼-- · 2019-01-11 00:10

NSTask

Using the NSTask class, your program can run another program as a subprocess and can monitor that program’s execution.

查看更多
登录 后发表回答