erlang - processes - ps show parent tree

How Do You Determine The PID of the Parent of a Process (4)

@Eridius' answer is the preferred way to do it. Requiring a process to register a name may have unintended side-effects such as increasing the visibility of the process not to mention the hassle of coming up with unique names when you have lots of processes.

I have a process in erlang that is supposed to do something immediately after spawn, then send the result back to the parent when it is finished. How do I figure out the PID of the process that spawned it?

If you want to do it wrong, here's our solution:

%% @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} ->
        _ ->
get_ancestors(undefined) ->
get_ancestors(Name) when is_atom(Name) ->

ancestors_from_dict([]) ->
ancestors_from_dict([{'$ancestors', Ancestors} | _Rest]) ->
ancestors_from_dict([_Head | Rest]) ->

You should pass self() to the child as one of the arguments to the entry function.

spawn_link(?MODULE, child, [self()]).

How to find the supervisor of an OTP process?

The data is hidden in the process dictionary (of any process spawned with proc_lib) under the entry '$ancestors':

1> proc_lib:spawn(fun() -> timer:sleep(infinity) end).
2> i(0,33,0).

Here the line that interests us is {dictionary,[{'$ancestors',[<0.31.0>]},.

Note that this is the kind of stuff you should rarely have any reason to use yourself. As far as I know, it's mostly used to handle clean termination in supervision trees rather than introspection for whatever code you have. Handle with care.

A cleaner way to do things without messing with OTP's sensible innards would be to have the supervisor pass its own pid as an argument to the process when starting it. This should be far less confusing for the people who'll read your code.