Erlang和process_flag(trap_exit,true) [英] Erlang and process_flag(trap_exit, true)

查看:725
本文介绍了Erlang和process_flag(trap_exit,true)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在观看Erlang上的Pragmatic Studio屏幕后,Supervisor上的最后一个视频提到,为了让主管得到关于其中一个孩子的通知,以便正确重新启动它,孩子应该注册 process_flag(trap_exit,true)。也许我只是误解了作者(并且机会非常高,我误解了),但是我认为主管自动地知道他们的孩子何时死亡(可能通过spawn_link或在后台类似的东西)。这真的有必要吗?何时应该在现实世界的情况下使用process_flag(trap_exit,true),因为文档明确指出以下内容:

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 children so it can properly restart it, the child should register with process_flag(trap_exit, true). Perhaps I just misunderstood the author (and chances are VERY high that I did misunderstand), but I thought supervisors automagically know when their children die (probably through spawn_link or something similar in the background). Is this really necessary? When should one use process_flag(trap_exit, true) in a real world case because the documentation explicitly states the following:

http://www.erlang.org/doc/man/erlang.html#process_flag-2


process_flag(trap_exit,Boolean)

process_flag(trap_exit, Boolean)


当trap_exit设置到达,到达进程的退出信号将转换为{'EXIT',From,Reason}消息,可作为普通消息接收。如果trap_exit设置为false,则如果接收到除正常之外的退出信号,则该进程退出,并将退出信号传播到其链接的进程。应用程序通常不会陷阱退出。``

When trap_exit is set to true, exit signals arriving to a process are converted to {'EXIT', From, Reason} messages, which can be received as ordinary messages. If trap_exit is set to false, the process exits if it receives an exit signal other than normal and the exit signal is propagated to its linked processes. Application processes should normally not trap exits.``



推荐答案

你有3个成语:

1 /我不在乎我的孩子进程是否死机:

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

spawn(...)

2 /我的子进程崩溃:

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

spawn_link(...)

3 /如果我的子进程终止(通常是否),我想收到一条消息:

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

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

请参阅此示例并尝试不同的值(与2或0相反以引发异常,并使用trap_exit):

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.

这篇关于Erlang和process_flag(trap_exit,true)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆