Erlang and process_flag(trap_exit, true)

前端 未结 3 1820
说谎
说谎 2020-12-28 16:25

After watching the Pragmatic Studio screen casts on Erlang, the last video on Supervisors mentioned that in order for a supervisor to get a notification about one of its chi

3条回答
  •  醉酒成梦
    2020-12-28 17:15

    You have 3 idioms:

    1/ I don't care if my child process dies:

    spawn(...)
    

    2/ I want to crash if my child process crashes:

    spawn_link(...)
    

    3/ I want to receive a message if my child process terminates (normally or not):

    process_flag(trap_exit, true),
    spawn_link(...)
    

    Please see this example and try different values (inverse with 2 or 0 to provoke an exception, and using trap_exit or not):

    -module(play).
    -compile(export_all).
    
    start() ->
        process_flag(trap_exit, true),
        spawn_link(?MODULE, inverse, [2]),
        loop().
    
    loop() ->
        receive
            Msg -> io:format("~p~n", [Msg])
        end,
        loop().
    
    inverse(N) -> 1/N.
    

提交回复
热议问题