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?
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
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With