[erlang-questions] How to find Pids of the children of a supervisor

zxq9 zxq9@REDACTED
Fri Dec 8 10:45:02 CET 2017

On 2017年12月07日 木曜日 13:33:36 Joe Armstrong wrote:
> I was asked the following in a direct mail to me:
> "Given two worker processes in a supervision tree, A and B, if A wants
> to message B, how should it obtain the pid of B ?"
> Pretty good question.
> I think the answer is to use supervisor:which_children/1 and to name
> the supervisor and all the children.
> Is the the best way? - does anybody have an example?

I tend to use a (semi) standard template of:


I wrote about it in a (poorly structured and unrevised) post here:

I'm going to take a stab at this frequently asked question here in email first, and maybe refine it into something worthy of a post on this specific subject later.

The worker_sup may or may not even be started, things might be linked/monitored together in arbitrary ways, etc, but the basic pattern seems to always wind up forming one way or another regardless how the project is designed to start with (before assumptions have been subjected to reality).

SOMETHING must be a named, universal interface to the service (from the perspective of other services in the system, assuming there is more than one), and very often the nature of the service itself is one where workers form arbitrary relationships amongst themselves.

In the case of a broadcast-type service amongst processes (a chat service or update notification system, for example) the connection handlers are one service and the channels themselves are components of another: no peer lookup is necessary except when it comes time to find the pid of a channel to send a subscription request to -- then you send the lookup request to the named service manager of the chat service.

In the case that the same chat or channelized service also supports private messaging, it would be natural for the connection handler's service manager to keep a registry of connected and active pids (which you would do anyway if you want to be able to inspect the system's active state in more interesting ways than merely looking up a list of child pids from the supervisor). So how to resolve a chat username to a pid? Any chat_client worker asks the chat_client_man -- and finds out maybe not just the pid, but also how long he's been logged on, whether he's logged on, IP, or whatever other `finger` type data might be tracked by the system.

The bottom line is that this little pyramid of processes seems to nearly always be needed to define a discrete service, and every time you need to find a sibling's pid the reason for finding it dictates that you have some custom tracking and query code surrounding the lookup -- and that means the natural place for a lookup is in the service manager in nearly every case.


More information about the erlang-questions mailing list