Skip to content

Instantly share code, notes, and snippets.

@leikind
Created November 18, 2011 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leikind/1377221 to your computer and use it in GitHub Desktop.
Save leikind/1377221 to your computer and use it in GitHub Desktop.
exit/1, exit/2, link, trap_exit
-module(trap).
-export([simple_exit_demo/0, kill_demo_v2/0, kill_demo/0, successfully_killing_a_non_system_process/0]).
listen() ->
receive
Message -> io:format("~p has caught a system message: ~p~n~n", [self(), Message]),
listen()
after 1000 ->
io:format("I, ~p, live on~n", [self()]),
listen()
end.
kill_demo() ->
Pid = spawn_link(fun()->
process_flag(trap_exit, true),
listen()
end),
% this will fail, the recipient process traps all exit signals
timer:sleep(3000),
io:format("Sending exit(Pid, please_die) ~p to ~n", [Pid]),
exit(Pid, please_die),
% "The kill reason acts as a special signal that can't be trapped."
timer:sleep(4000),
io:format("Sending exit(Pid, kill) ~p to ~n", [Pid]),
exit(Pid, kill).
%%%%%%%
kill_demo_v2() ->
Pid = spawn_link(fun()->
process_flag(trap_exit, true),
listen()
end),
process_flag(trap_exit, true),
% this will fail, the recipient process traps all exit signals
timer:sleep(3000),
io:format("Sending exit(Pid, please_die) ~p to ~n", [Pid]),
exit(Pid, please_die),
% "The kill reason acts as a special signal that can't be trapped."
timer:sleep(4000),
io:format("Sending exit(Pid, kill) ~p to ~n", [Pid]),
exit(Pid, kill),
receive
Message -> io:format("~p has caught a system message: ~p~n~n", [self(), Message])
end.
%%%%%%%
% seems like in order to send exit() from A to B they needn't be linked (spawn instead of spawn_link)
successfully_killing_a_non_system_process() ->
Victim = spawn(fun()->
io:format("Victim process alive (~p)~n", [self()]),
receive
Res -> Res
after 2000 ->
% this will never happen, the process will be killed before
io:format("Dying my own natural death (~p)~n", [self()])
end
end),
% this will fail, the recipient process traps all exit signals
timer:sleep(1000),
io:format("Sending exit(Victim, please_die) to ~p ~n", [Victim]),
exit(Victim, please_die).
%%%%%%%%
simple_exit_demo() ->
spawn(fun() -> start_processes() end).
start_processes() ->
process_flag(trap_exit, true),
spawn_link(fun() -> timer:sleep(1000) end),
spawn_link(fun() -> timer:sleep(2000), exit(exiting_for_a_reason) end),
spawn_link(fun() -> timer:sleep(3000), exit(normal) end),
spawn_link(fun() -> timer:sleep(4000), 1 / 0 end),
spawn_link(fun() -> timer:sleep(5000), erlang:error(raising_error) end),
spawn_link(fun() -> timer:sleep(6000), throw(throwing_error) end),
listen_to_exits().
listen_to_exits() ->
receive
Message -> io:format("Caught a system message: ~p~n~n", [Message]),
listen_to_exits()
after 7000 ->
io:format("Show's over~n")
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment