Basic "What am I doing wrong?" question (Tuple argument to spawn? Dead pid intead of a runtime error?)
Luke Gorrie
luke@REDACTED
Fri Feb 14 18:42:07 CET 2003
"Jonathan Coupe" <jonathan@REDACTED> writes:
> -module(ctr).
> -export([start/1, loop/1, increment/1, value/1, name/1, stop/1]).
>
>
> start(Name) ->
> Pid = spawn(counter, loop, [{Name, 0}]),
^^^^^^^
There's the trouble: it should be 'ctr' (the name of the module)
instead of 'control'. Alternatively you could use the built in macro
?MODULE, which expands to the module name as an atom.
Also, if you use spawn_link then a crash of the new process will
propagate back to you, so you can see the error in the shell.
I also notice that 'value' and 'name' must take a pid, and not a
registered name. The reason is that otherwise the reply will not match
in the receive - you would be trying to match the name of the process,
but it would send you its pid instead. You could change the value
function to accept either a pid or a name like this:
value(Name) when atom(Name) -> % lookup registered names
value(process_called(Name));
value(Pid) when pid(Pid) ->
Pid ! {self(), value},
receive
{Pid, Value} ->
Value
end.
%% Return the process registered as Name, or crash if there isn't one.
process_called(Name) when atom(Name) ->
case whereis(Name) of
undefined -> exit({no_process, Name});
Pid -> Pid
end.
Cheers,
Luke
More information about the erlang-questions
mailing list