8

OTPプロセスがスーパーバイザーのpidを見つけることを可能にする機能はありますか?

4

2 に答える 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 に答える