在启动 start_child 调用的进程中注册子进程

发布于 2024-10-06 02:07:38 字数 301 浏览 0 评论 0原文

我有一个逻辑模块,告诉主管启动子进程。我需要将这些孩子的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晒暮凉 2024-10-13 02:07:38

一个问题是您有 ChildPid 并且孩子现在可能已经死了。因此,通过 cast 向其发送消息将意味着消息丢失。通过调用,您将因{'EXIT', noproc}而崩溃,除非您从调用中捕获它。您的解决方案必须考虑到 Pid 可能在您发送消息后就早已消失。通常是忽略消息丢失,让自己崩溃,或者解决问题然后继续。

有几个选择。这是一个松散的清单:

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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文