题
是否有允许OTP流程找到其主管PID的功能?
解决方案
数据隐藏在流程字典中(在带有的任何过程中 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>]},
.
请注意,这是您很少有理由使用自己的东西。据我所知,它主要用于处理监督树中的清洁终止,而不是内省的任何代码。小心轻放。
一种更干净的方法来做事而不弄乱OTP的明智的内脏是 让主管在开始时将其PID作为论点传递给该过程. 。对于那些会阅读您的代码的人来说,这应该令人困惑。
其他提示
如果您想做错了,这是我们的解决方案:
%% @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).
不隶属于 StackOverflow