How to get parent of an erlang process

The erlang application monitor, i.e. appmon, could build a process tree for an erlang application. To build such a tree, we need to find out all processes that belong to the same application and the hierarchy relations between those processes. We enumerate all processes and call application:application(Pid) on each pid to construct some disjoint sets for applications. And we call erlang:process_info(Pid, dictionary) on each pid to get its ancestor processes. Processes created by proc_lib:spawn* store ancestor information in their process dictionaries.

11> process_info(whereis(timer_server),dictionary).

The following code fragment is quoted from otp_src_R14B01/lib/stdlib/src/proc_lib.erl:

spawn(M,F,A) when is_atom(M), is_atom(F), is_list(A) ->
    Parent = get_my_name(),
    Ancestors = get_ancestors(),
    erlang:spawn(?MODULE, init_p, [Parent,Ancestors,M,F,A]).

init_p(Parent, Ancestors, M, F, A) when is_atom(M), is_atom(F), is_list(A) ->
    put('$ancestors', [Parent|Ancestors]),
    put('$initial_call', trans_init(M, F, A)),
    init_p_do_apply(M, F, A).

get_ancestors() ->
    case get('$ancestors') of
    A when is_list(A) -> A;
    _                 -> []

The following code fragment is quoted from otp_src_R14B01/lib/stdlib/src/gen_server.erl:

get_parent() ->
    case get('$ancestors') of
    [Parent | _] when is_pid(Parent)->
        [Parent | _] when is_atom(Parent)->
    _ ->

Generally there is no standard way to find the parent of a certain process. If you want a process to send message to its parent, you’d better pass the parent pid as an argument to spawn*(), and the child process should memorize this pid for later use.

This entry was posted in erlang and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s