Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Registering a child in the process that initiated the start_child call

I have a logic module that tells a supervisor to start child processes. I need to store those childrens pid in the logic modules state. But I also need to update a childs pid if the supervisor restarts it.

So I can't use the return value pid from the start_child call, since that will only give me the pid on the first start, not the restarts. Right now I make the child process call a register function (updates state with new pid) in the logic module from the childs init function. That way the logic module can update the pid in its state whenever a process is restarted. The logic module is a gen_server and I'm doing a cast when i register the child process.

Can anyone see a problem with this and are there any other more "proper" way of doing it?

like image 317
JoGr Avatar asked Dec 03 '10 17:12

JoGr


1 Answers

One problem is that you have the ChildPid and the child might be dead by now. So sending it a message through a cast will mean the message is lost. And through a call you will crash yourself with an {'EXIT', noproc} unless you catch it out of the call. Your solution must take into account that a Pid might be long gone the instant you send a message. Usually by ignoring that the message is lost, by crashing yourself, or by remedying the problem and then go on.

There are a couple of options. This is a loose list:

  • Do as you do. Let the childs register themselves.
  • Let the logic module have a monitor on the child. That way you know if it dies.
  • Use Erlang Solutions gproc module: https://github.com/esl/gproc which gives you a neat interface to an ETS table keeping track of the information. Note that you can look up a pid in gproc and await its arrival if the process is just restarting.
  • Use supervisor:which_children to find the relevant child.
  • Roll your own ETS table as a variant of gproc
  • local names have to be atoms, but globally registered names can be any term (they are stored internally in a ETS table looking somewhat like gproc's, see the global_name_server in kernel/stdlib). Use the global structure to track the pids in question.
like image 55
I GIVE CRAP ANSWERS Avatar answered Oct 22 '22 07:10

I GIVE CRAP ANSWERS