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

1.2k views Asked by At

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...

2

There are 2 answers

4
zxq9 On BEST ANSWER

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.
1
Pascal On

If you have the string "" to identify a pid, it is

  • either because you are working in the shell, and you use the representation you see, and you forgot to store this pid in a variable. Then simply use pid(X,Y,Z) to get it;
  • either because you did something like io_lib:format("~p",[Val]) where Val is the pid or a an erlang term which contain this pid. Then simply assign the pid to a variable (directly or extracting it from the term). It can be stored in an ets, send to another process without transformation

You should avoid to use the shell (or string) representation. One reason is that this representation is different when you ask the pid of one process from 2 different nodes as shown in the next screen capture.

enter image description here