在启动 start_child 调用的进程中注册子进程
我有一个逻辑模块,告诉主管启动子进程。我需要将这些孩子的 pid 存储在逻辑模块状态中。但如果主管重新启动它,我还需要更新子进程的 pid。
所以我不能使用 start_child 调用的返回值 pid,因为这只会给我第一次启动时的 pid,而不是重新启动时的 pid。现在,我让子进程从子进程的 init 函数调用逻辑模块中的寄存器函数(用新的 pid 更新状态)。这样,每当进程重新启动时,逻辑模块就可以更新 pid 的状态。逻辑模块是 gen_server,当我注册子进程时我正在进行强制转换。
任何人都可以看到这个问题,还有其他更“正确”的方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个问题是您有
ChildPid
并且孩子现在可能已经死了。因此,通过cast
向其发送消息将意味着消息丢失。通过调用
,您将因{'EXIT', noproc}
而崩溃,除非您从调用
中捕获它。您的解决方案必须考虑到Pid
可能在您发送消息后就早已消失。通常是忽略消息丢失,让自己崩溃,或者解决问题然后继续。有几个选择。这是一个松散的清单:
监视器
。这样你就知道它是否死了。supervisor:which_children
查找相关的子项。gproc
的变体进行滚动,kernel/stdlib
中的 global_name_server)。使用全局结构来跟踪有问题的 pid。One problem is that you have the
ChildPid
and the child might be dead by now. So sending it a message through acast
will mean the message is lost. And through acall
you will crash yourself with an{'EXIT', noproc}
unless you catch it out of thecall
. Your solution must take into account that aPid
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:
monitor
on the child. That way you know if it dies.supervisor:which_children
to find the relevant child.gproc
kernel/stdlib
). Use the global structure to track the pids in question.