I would not try to access the child by Pid but instead register/2 the child process under a name, so it's accessible regardless of the actual Pid.
Using the code from the answer you reference, a simple way of doing this is to add register(ch1, self()),
to the init procedure of the child. This would give, for ch1.erl
:
init(_Args) ->
io:format("ch1 has started (~w)~n", [self()]),
% register a name to this process
register(child, self()),
{ok, ch1State}.
This registers the pid of the child self()
to the name child
We can see it works:
1> root_sup:start_link().
{ok,<0.34.0>}
2> supervisor:start_child(root_sup, []).
ch1 has started (<0.36.0>)
{ok,<0.36.0>}
3> lists:filter(fun(X) -> X == child end, registered()).
[child]
we indeed have a process registered under the name of child
.
4> gen_server:cast(child, calc).
result 2+2=4
and it is a correct process running the code from ch1.erl
.
Let us crash this process, by invoking the bad code:
5> gen_server:cast(child, calcbad).
result 1/0
ok
ch1 has started (<0.41.0>)
6>
=ERROR REPORT==== 28-Oct-2012::01:31:30 ===
** Generic server <0.36.0> terminating
** Last message in was {'$gen_cast',calcbad}
** When Server state == ch1State
** Reason for termination ==
** {'function not exported',
[{ch1,terminate,
[{badarith,
[{ch1,handle_cast,2,[{file,"ch1.erl"},{line,27}]},
{gen_server,handle_msg,5,
[{file,"gen_server.erl"},{line,607}]},
{proc_lib,init_p_do_apply,3,
[{file,"proc_lib.erl"},{line,227}]}]},
ch1State],
[]},
{gen_server,terminate,6,[{file,"gen_server.erl"},{line,722}]},
{proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,227}]}]}
So the child, the process <0.36.0>
crashed, and a new child <0.41.0>
was started to assume the duties of the deceased <0.36.0>
. Since this new process is registered under the same name, calc
will work again:
6> gen_server:cast(child, calc).
result 2+2=4
ok
Note that this does not guarantee that the gen_server:cast/2
s always result in the execution of the corresponding code because the child might have been killed just now and the new process still was not started (registered in fact).
You might want to refer to the excellent Programming Erlang: Software for a Concurrent World by Joe Armstrong for more details about process registration, supervisors, OTP and more. Many details can also be found in the online documentation of OTP.