代码之家  ›  专栏  ›  技术社区  ›  Alexey Romanov

如何找到OTP流程的主管?

  •  7
  • Alexey Romanov  · 技术社区  · 15 年前

    是否有允许OTP进程查找其主管的pid的函数?

    2 回复  |  直到 15 年前
        1
  •  13
  •   I GIVE TERRIBLE ADVICE    15 年前

    数据隐藏在进程字典中(由 proc_lib )在入口下面 '$ancestors' :

    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',[<0.31.0>]}, .

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

    一个更干净的方式来做的事情,而不打乱检察官的理智的内脏将是 . 对于那些会阅读您的代码的人来说,这应该不会太混乱。

        2
  •  1
  •   YOUR ARGUMENT IS VALID    15 年前

    %% @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).