Search code examples
erlangerlang-shell

Why doesn't spawn link cause the calling process to die?


From the example given here, Erlang and process_flag(trap_exit, true)

-module(play).
-compile(export_all).

start() ->
    process_flag(trap_exit, true),
    spawn_link(?MODULE, inverse, [***0***]),
    loop().

loop() ->
    receive
        Msg -> io:format("~p~n", [Msg])
    end,
    loop().

inverse(N) -> 1/N.

If I run it as,

A = spawn(play, start, []).

The spawned process <0.40.0> dies as it is suppose to but the main process (A <0.39.0>) which spawned it doesn't die.

{'EXIT',<0.40.0>,{badarith,[{play,inverse,1,[{file,"play.erl"},{line,15}]}]}}
<0.39.0>
i().
....
....
<0.39.0>              play:start/0                           233       19    0
                  play:loop/0                              1              

A does get an exit signal (not an exit message since A is not trapping exit) then why doesn't it exit?


Solution

  • The reason for this is that you set a trap_exit flag to true which means this process will get {'EXIT', FromPid, Reason} message instead of being killed. Just remove process_flag(trap_exit, true) or in case of receiving this type of message, kill it.

    You can read about it here.