How do you use posix_spawn to replace the deprecated 'system' to launch opendiff in Objective-C?
Asked Answered
B

2

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.

Babbittry answered 20/11, 2014 at 18:20 Comment(0)
G
16

Using posix_spawn(), to answer your question:

#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);

Or, you could use 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];

If you don't need it to be synchronous, just remove the call to waitpid() (make sure to call it somewhere else, or you'll end up with a zombie process until your app exits) or [task waitUntilExit].

Gadolinium answered 5/1, 2015 at 15:3 Comment(0)
A
1

Swift 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()
}
Acidimeter answered 8/11, 2017 at 0:58 Comment(1)
The Process API is not available on iOS (OP's question lists iOS8)Heirship

© 2022 - 2024 — McMap. All rights reserved.