Preventing multiple instances through register/2

Richard Carlsson <>
Mon May 15 09:16:56 CEST 2006


Jeff Crane wrote:
 > Can anyone explain to me why the atom
 > already_registered does not echo to the screen, but
 > the io:format (commented out) does?

If you do as in your example:

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

then the final value (which is echoed to the screen when
you run the code from the shell) is that of the last expression,
namely 'Pid ! exit' (and the value of that is just 'exit').
When you run several expressions separated by comma, all the
results except the last are thrown away. This should work:

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

*But* you are still doing the registration from the "wrong"
process, which makes it more complicated than it needs to be.
Try something like this:

   start() ->
       Pid = spawn(?MODULE, process, [self()] end),
       receive
           {Pid, Result} -> Result
       end.

   process(Parent) ->
       case catch register(test_server, self()) of
           true ->
               Parent ! {self(), ok},
               start_work();
           _ ->
               Parent ! {self(), error},
               exit(error)
       end.

   start_work(...) -> ...

> Without registering, how do you send messages to a PID
> from the command line?

You can do something like this:

   1> Pid = spawn(mymodule, myprocessfunction, [1,2,3]).

   2> Pid ! message.

but if you don't know the Pid, then you don't know it.
Look at it as a sort of access control.

	/Richard




More information about the erlang-questions mailing list