Erlang: ways to specify the server in gen_server:call

19 Apr 2023 15:40 erlang

You can gen_server:call in a bunch of different ways.

If you have a process ID:

gen_server:call(Pid, Req).    % local by pid

If it’s registered locally:

gen_server:call(Name, Req).   % local by name -- uses whereis(Name)
gen_server:call({local, Name}, Req).    % local by name -- uses whereis(Name)

Note that {local, Name} is undocumented – it’s not listed under server_ref() and might not always be supported.

If it’s registered in global:

gen_server:call({global, Name}, Req).   % global by name -- uses global:whereis_name(Name)

If it’s registered in some other process registry:

gen_server:call({via, Registry, Name}, Req).  % via by name -- uses Registry:whereis_name(Name)

global uses the same interface as via:

gen_server:call({via, global, Name}, Req).  % global uses the same API as user-defined registries

You can also call named processes on remote nodes (or on the local node):

gen_server:call({Name, LocalNode}, Req).   % local by name -- uses whereis(Name)
gen_server:call({Name, RemoteNode}, Req).   % remote by name -- uses erlang:send({Name, RemoteNode}, ...)