0

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?

Avi L
  • 1,558
  • 2
  • 15
  • 33
  • https://stackoverflow.com/questions/33423993/hanging-nstask-using-waituntilexit – matt Jul 19 '20 at 18:54
  • https://stackoverflow.com/questions/34996937/how-to-safely-use-nstask-waituntilexit-off-the-main-thread – matt Jul 19 '20 at 18:54
  • @matt, I tried all your recommended answers but with no luck, I finally found the problem: opening .app file exit immediately, however opening the /Contents/MacOS/ file will wait till the app finish execution. (I will write it as an answer). – Avi L Jul 20 '20 at 06:26

1 Answers1

0

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];
Avi L
  • 1,558
  • 2
  • 15
  • 33
  • If this answer solves your problem, please accept it (even if it is your question), it's perfectly valid. It helps to keep SO clean and it also saves time of other people, because they see it as answered and can help with other questions. Thanks. – zrzka Jul 20 '20 at 11:06
  • Yeah I know, I'm waiting for tomorrow since SO only allows me to do that then... – Avi L Jul 20 '20 at 11:57