Search code examples
processerlangmessage-passing

Is it possible to send a message to an unregistered processes in Erlang?


I am aware that you can preform simple message passing with the following:

self() ! hello. 

and you can see the message by calling:

flush().

I can also create simple processes in functions with something like:

spawn(module, function, args).

However I am not clear how one can send messages to the processes with out registering the Pid.

I have seen examples showing that you can pattern match against this in the shell to get the Pid assigned to a var, so if i create a gen_server such as:

...
start_link() ->
  gen_server:start_link(?MODULE, init, []).

init(Pid) ->
  {ok, Pid}.
...

I can then call it with the following from the shell:

{ok, Pid} = test_sup:start_link().
{ok,<0.143.0>}
> Pid ! test.
test

So my question is, can you send messages to Pids in the form <0.0.0> with out registering them to an atom or variable in the shell? Experimenting and searching as proved fruitless...


Solution

  • If you happen to need to send a message to a Pid based on the textual representation of its Pid, you can do (assuming the string is "<0.42.0>"):

    list_to_pid("<0.42.0>") ! Message
    

    This is almost only useful in the shell (where you can see the output of log messages or monitor data from something like Observer); any spawned process should normally be a child of some form of parent process to which it is linked (or monitored).

    As for sending a message to something you just spawned, spawn returns a Pid, so you can assign it directly to a variable (which is not the same as registering it):

    Pid = spawn(M, F, A),
    Pid ! Message.