11

This line of code:

system("/Applications/Xcode.app/Contents/Developer/usr/bin/opendiff /Users/LukeSkywalker/Documents/doc1.rtf /Users/LukeSkywalker/Documents/doc2.rtf");

gives me this warning:

'system' is deprecated: first deprecated in iOS 8.0 - Use posix_spawn APIs instead.

I've read a little bit about posix_spawn, but I can't figure out what an equivalent line of code using posix_spawn would look like.

Any help or links to samples would be appreciated.

4

2 回答 2

16

使用posix_spawn(), 回答您的问题:

#include <spawn.h>
extern char **environ;

(...)

pid_t pid;
char *argv[] = {
    "/Applications/Xcode.app/Contents/Developer/usr/bin/opendiff",
    "/Users/LukeSkywalker/Documents/doc1.rtf",
    "/Users/LukeSkywalker/Documents/doc2.rtf",
    NULL
};

posix_spawn(&pid, argv[0], NULL, NULL, argv, environ);
waitpid(pid, NULL, 0);

或者,您可以使用 NSTask:

NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/Applications/Xcode.app/Contents/Developer/usr/bin/opendiff";
task.arguments = [NSArray arrayWithObjects:
                  @"/Users/LukeSkywalker/Documents/doc1.rtf",
                  @"/Users/LukeSkywalker/Documents/doc2.rtf",
                  nil];
[task launch];
[task waitUntilExit];

如果您不需要它是同步的,只需删除对的调用waitpid()(确保在其他地方调用它,否则在您的应用退出之前您将得到一个僵尸进程)或[task waitUntilExit].

于 2015-01-05T15:03:42.480 回答
1

斯威夫特 3,Xcode 8.3.1

func system(_ command: String) {
    var args = command.components(separatedBy: " ")
    let path = args.first
    args.remove(at: 0)

    let task = Process()
    task.launchPath = path
    task.arguments = args
    task.launch()
    task.waitUntilExit()
}
于 2017-11-08T00:58:57.893 回答