Preventing multiple instances through register/2

Vlad Dumitrescu <>
Mon May 15 09:04:11 CEST 2006


Hi,

If you're using a gen_server, you can also use start_link/4 or start/4 with
a first argument of {local, Name} or {global, Name} and the details will be
handled for you.

If it's a server you implement yourself, do this:

start() ->
    spawn(?MODULE, init, []).

init() ->
    case (catch register(test_server, self()) of
        {'EXIT', _} ->
            already_registered;  % process ends here
        _ ->
            load_accounts()
    end.

>From the shell you can send test_server ! Msg, which will find either the
newly spawned process or the older one that was running.

In your code, already_registered isn't returned from the function, so the
value is lost
The return is the value of "Pid ! exit", which is the atom 'exit'.

                       already_registered,
%%                      io:format(" test_server:already
registered:~p~n",[Err]),
                       %% Kill spawned process, via msg
                       Pid ! exit;

hope this helps,
/Vlad
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20060515/696875ed/attachment.html>


More information about the erlang-questions mailing list