[erlang-questions] Accessing a gen_server function from another process

Martin Karlsson <>
Fri Jul 28 00:34:22 CEST 2017


>Generally, gen_server:start_link returns a tuple of the form {ok, Pid}, where Pid is used for API calls to the server. Now, Erlang doesn’t have any good way of storing state, such as a variable to hold this Pid. So, If I have a function that every once in a while needs to call this API, but that API needs a Pid, and theres no way to get a Pid without starting a whole new server… how is this done?
>

Hi,

Normally this is done in one of two ways (which really are the same but
one is built-in).

1) You register the process with a unique name which is an atom. Either
by yourself or by starting the gen_server as a named server.

gen_server:start_link({local, my_name}, Module, Args, Options).

Then:

gen_server:call(my_name, hello).

You can also register a pid with a name using erlang:register/2.

{ok, Pid} = gen_server:start_link(Module, Args, Options),
true = register(my_name, Pid).

This is normally used when you have static gen_servers which you want to
call throughout your code without caring about the pid.


2) You store the pid in a lookup registry of some sort and then lookup
the pid before you call your gen_server. This is often done if you have
more dynamic processes and process names or want to use something
different than an atom to lookup the pid.

The lookup registry in itself can be a named process (as per 1) where
you can register and lookup your pids. It is a pretty good exercise to
implement it.

For example:

{ok, Pid} = gen_server:start_link(Module, Args, Options),
ok = my_registry:register(<<"whatevername">>, Pid)

To call:

{ok, Pid} = my_registry:lookup(<<"whatevername">>),
gen_server:call(Pid, hello).

There are a number of process registry libraries out there; gproc
(https://github.com/uwiger/gproc) being one of the more well known. I'd
start by implementing my own though as it gives you a better
understanding how things work.

I haven't looked it up but I think that learnyousomeerlang will bring up
this subject too.


More information about the erlang-questions mailing list