是否有功能可以让 OTP 进程找到其主管的 pid?
问问题
1700 次
2 回答
14
数据隐藏在条目下的进程字典(由 生成的任何进程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 作为参数传递给进程。对于将阅读您的代码的人来说,这应该不会让人感到困惑。
于 2010-11-09T11:39:18.260 回答
1
如果你想做错了,这里是我们的解决方案:
%% @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).
于 2010-11-10T14:40:52.567 回答