【问题标题】:How to find the supervisor of an OTP process?如何找到 OTP 流程的主管?
【发布时间】:2011-05-07 03:33:45
【问题描述】:

是否有函数可以让 OTP 进程找到其主管的 pid?

【问题讨论】:

  • 不知道,但是你可以得到链接的进程,主管就是其中之一。

标签: erlang erlang-otp erlang-supervisor


【解决方案1】:

数据隐藏在条目'$ancestors' 下的进程字典(由proc_lib 生成的任何进程)中:

1> proc_lib:spawn(fun() -> timer:sleep(infinity) end).
<0.33.0>
2> i(0,33,0).
[{current_function,{timer,sleep,1}},
 {initial_call,{proc_lib,init_p,3}},
 {status,waiting},
 {message_queue_len,0},
 {messages,[]},
 {links,[]},
 {dictionary,[{'$ancestors',[<0.31.0>]},
              {'$initial_call',{erl_eval,'-expr/5-fun-1-',0}}]},
 {trap_exit,false},
 {error_handler,error_handler},
 {priority,normal},
 {group_leader,<0.24.0>},
 {total_heap_size,233},
 {heap_size,233},
 {stack_size,6},
 {reductions,62},
 {garbage_collection,[{min_bin_vheap_size,46368},
                      {min_heap_size,233},
                      {fullsweep_after,65535},
                      {minor_gcs,0}]},
 {suspending,[]}]

我们感兴趣的线路是{dictionary,[{'$ancestors',[&lt;0.31.0&gt;]},

请注意,您应该很少有任何理由自己使用这种东西。据我所知,它主要用于处理监督树中的干净终止,而不是对您拥有的任何代码进行内省。小心处理。

在不影响 OTP 合理内部结构的情况下做事的一种更简洁的方法是让主管在启动进程时将其自己的 pid 作为参数传递给进程。对于将阅读您的代码的人来说,这应该不会令人困惑。

【讨论】:

  • 我也会选择主管 pid 的通行证。实现和维护更简单。
【解决方案2】:

如果你想做错了,这里是我们的解决方案:

%% @spec get_ancestors(proc()) -> [proc()]
%% @doc Find the supervisor for a process by introspection of proc_lib
%% $ancestors (WARNING: relies on an implementation detail of OTP).
get_ancestors(Pid) when is_pid(Pid) ->
    case erlang:process_info(Pid, dictionary) of
        {dictionary, D} ->
            ancestors_from_dict(D);
        _ ->
            []
    end;
get_ancestors(undefined) ->
    [];
get_ancestors(Name) when is_atom(Name) ->
    get_ancestors(whereis(Name)).

ancestors_from_dict([]) ->
    [];
ancestors_from_dict([{'$ancestors', Ancestors} | _Rest]) ->
    Ancestors;
ancestors_from_dict([_Head | Rest]) ->
    ancestors_from_dict(Rest).

【讨论】:

    猜你喜欢
    • 2013-07-08
    • 2014-07-10
    • 2017-04-09
    • 2016-01-14
    • 2020-09-20
    • 2017-09-19
    • 2016-01-08
    • 2021-05-12
    • 2016-01-16
    相关资源
    最近更新 更多