Suppose you have an OTP process whose completion you want to synchronously wait on (where "completion" may be a normal exit or a crash, stop, etc.).
Suppose further that for business reasons, you can't spawn this process with Task.async/1
or related Task
utilities—it has to be a "normal" process not dependent on Task.await/2
.
Is there a better way to do this than simply intermittently polling Process.alive?/1
? This strikes me as the sort of thing there's probably an established pattern for, but for the life of me I can't find it.
def await(pid, timeout) when timeout <= 0 do
if Process.alive?(pid) do
Process.exit(pid, :kill) # (or however you want to handle timeouts)
end
end
@await_sleep_ms 500
def await(pid, timeout) do
# Is there a better way to do this?
if Process.alive?(pid) do
:timer.sleep(@await_sleep_ms)
await(pid, subtract_timeout(timeout, @await_sleep_ms))
end
end
Process.monitor/1
andreceive/1
with atimeout: :infinity
and pattern-matching PID in message handler is a way to go. – MultureProcess.monitor/1
is exactly what I was looking for! – Naples