Skip to content

Instantly share code, notes, and snippets.

@rinaldifonseca
Forked from MachinesAreUs/example run
Last active February 24, 2024 02:59
Show Gist options
  • Save rinaldifonseca/f55cbb1a941869f2bda6ac0eab91f167 to your computer and use it in GitHub Desktop.
Save rinaldifonseca/f55cbb1a941869f2bda6ac0eab91f167 to your computer and use it in GitHub Desktop.
Demonstration of trapping exits in Elixir
iex(2)> pid = spawn Traps, :init, []
waiting to die...
#PID<0.92.0>
Nobody tried to kill me! ^_^
waiting to die...
Nobody tried to kill me! ^_^
waiting to die...
iex(3)> Process.exit pid, :normal
true
(⊙_⊙') somebody tried to kill me! {:EXIT, #PID<0.88.0>, :normal}
waiting to die...
Nobody tried to kill me! ^_^
waiting to die...
Nobody tried to kill me! ^_^
waiting to die...
Nobody tried to kill me! ^_^
waiting to die...
iex(4)> Process.exit pid, :muereeeeee
(⊙_⊙') somebody tried to kill me! {:EXIT, #PID<0.88.0>, :muereeeeee}
true
waiting to die...
Nobody tried to kill me! ^_^
waiting to die...
Nobody tried to kill me! ^_^
waiting to die...
Nobody tried to kill me! ^_^
waiting to die...
iex(5)> Process.exit pid, :kill
true
iex(6)>
defmodule Traps do
def init do
Process.flag :trap_exit, true
loop()
end
def loop do
IO.puts "waiting to die..."
receive do
msg ->
IO.puts "(⊙_⊙') somebody tried to kill me! #{inspect msg}"
after 1000 ->
IO.puts "Nobody tried to kill me! ^_^"
end
loop
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment