Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hanging NSTask using waitUntilExit

I need to use NSTask synchronously, however I find that occasionally my task hangs under the 'waitUntilExit' command. I wonder if there is a graceful way--an error handling method--to terminated the hanging task so I can re-launch another?

like image 592
Antony Avatar asked Oct 29 '15 20:10

Antony


2 Answers

Note that if the task being run via NSTask fills the output pipe then the process will hang, effectively blocking waitUntilExit from returning.

You can prevent this situation by calling

[task.standardOutput.fileHandleForReading readDataToEndOfFile];

before calling

[task waitUntilExit];

This will cause the output pipe's data to be read until the process writing to the output pipe closes it.

Example code demonstrating the issue and various solutions:

https://github.com/lroathe/PipeTest

like image 191
Lane Roathe Avatar answered Sep 21 '22 14:09

Lane Roathe


You could launch the task using -[task launch] and then poll periodically on its isRunning property to check whether it has already finished. If it has not finished after a given time interval, you can call -[task terminate] to terminate it. This requires that the task you start does not ignore the SIGTERM signal.

If however polling for task termination is too inefficient in your case, you could setup a dispatch source of type DISPATCH_SOURCE_TYPE_PROC after you have launched your task. This source then asynchronously calls its event block when the task terminates:

dispatch_source_create(DISPATCH_SOURCE_TYPE_PROC, task.processIdentifier, DISPATCH_PROC_EXIT, dispatch_get_main_queue());
like image 29
Frank Illenberger Avatar answered Sep 20 '22 14:09

Frank Illenberger