objective-cmacosnstask

Run NSTask synchronously


I have an .app file that I'm running through NSTask and I wish the thread to be blocked till .app execution is over.

My current code is:

NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/bin/bash";
task.arguments = [NSArray arrayWithObjects:@"-c", "/usr/bin/open myApp.app", nil];
[task launch];
[task waitUntilExit]; // doesn't guarantee task will wait until exit according to docs

I know I can use NSTask.terminationHandler but since I have a lot of tasks I don't want to get into a callback hell situation (and also I don't care if everything will run sync and take some time)

(I also tried adding nohup to the execution command but it didn't made the affect i wanted.)

Is there a way to execute NSTask synchronously and wait until execution is over?


Solution

  • It seems that the problem was in the open command which executes the app and return context even if execution is not over.

    I found out that open has a -W argument:

    -W, --wait-apps Blocks until the used applications are closed (even if they were already running).

    adding this argument solved my problem. final code:

    NSTask *task = [[NSTask alloc] init];
    task.launchPath = @"/bin/bash";
    task.arguments = [NSArray arrayWithObjects:@"-c", "/usr/bin/open -W myApp.app", nil];
    [task launch];
    [task waitUntilExit];