Naming Our Processes

Understand how and when to name an Elixir process.

How to name a process

Although a PID is displayed as three numbers, it contains just two fields. The first number is the node ID, and the next two numbers are the low and high bits of the process ID. When we run a process on our current node, its node ID will always be 0. However, when we export a PID to another node, the node ID is set to the number of the node on which the process lives.

That works well once a system is up and running and everything is knitted together. If we want to register a callback process on one node and an event-generating process on another, we just give the callback PID to the generator.

But how can the callback find the generator in the first place? One way is for the generator to register its PID, giving it a name. The callback on the other node can look up the generator by name, using the PID that comes back to send messages to it.

Here’s an example. Let’s write a simple server that sends a notification about every two seconds. To receive the notification, a client has to register with the server. And we’ll arrange things so that clients on different nodes can register.

While we’re at it, we’ll do a little packaging so that to start the server, we run Ticker.start, and to start the client, we run Client.start. We’ll also add an API, Ticker.register, to register a client with the server.

Here’s the server code:

Get hands-on with 1200+ tech skills courses.