How do you send message to other process without their pid (without genserver too)

Hi , I am pretty new, I tried hard to find the answer on the internet but in vain.

In short :

Can I send messages to (non-genserver) processes without knowing their pid ?

long :

As far as I understood , to send messages from a process to another process you need “to be there” when one of the process is created, store the pid and pass it to the other processes that need to interact with it.

  • if the other process is created after you can pass the pid into its init arguments
  • or you store the other process’s pid and you send it one to another and process will receive it.
    … but if one process is restarted then it might be complicated to keep every process up to date.

When it comes to gen servers, you can just call its method API function without passing argument and some black magic will figure out the rest.
How difficult would it be to add that feature to custom a process
?
thanks

You can do that by f.e. Process.register (Process — Elixir v1.13.4).

Let’s say you create 2 or more of these processes. What kind of black magic can figure out to which process you intend to send your message?

That being said, I’d encourage you to read the OTP guide Introduction to Mix — Elixir v1.16.0-rc.0

This contains information on named processes. If you give a process a name you can send messages to that name instead of to the pid.

Then, if the process restart , I can access it with the same name even if the pid “changed” …?

There is no black magic involved. In your GenServer you probably copy/pasted code like this:

  @doc false
  def start_link(default) when is_list(default) do
    GenServer.start_link(__MODULE__, default, name: __MODULE__)
  end

That’s the name registration right there. A normal process can do the same thing. The documentation is here:
https://hexdocs.pm/elixir/1.15.7/GenServer.html#module-name-registration

4 Likes

hoooo … I have read registration, and have looked into gen-server details but until now I could make it click.
I got it now, thank you very much everyone.