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

I know that you can perform simple messaging 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 don't understand how one can send messages to processes without registering Pid.

I've seen examples showing that you can pattern match against this in the shell to get the Pid assigned to var, so if I create a gen_server like:

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

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

      

Then I can call it from the shell from within the shell:

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

      

So my question is, can you post messages to Pids in the form <0.0.0> without registering them with an atom or variable in the shell? Experimenting and searching has proven fruitless ...

+3


source to share


2 answers


If you need to send a message to a Pid based on the textual representation of its Pid, ​​you can do (if 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 an Observer); any spawned process should usually be a child of some parent process to which it is associated (or controlled).



As for sending a message to what you just spawned, it 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.

      

+4


source


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

  • or because you are in a shell and are using the view you see and forgot to store that pid in a variable. Then just 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 the erlang term containing that pid. Then just assign pid to the variable (either directly or by extracting it from that term). It can be saved in ets, sent to another process without conversion.


You should avoid using shell (or string) view. One reason is that this view is different when you ask for the pid of one process from two different nodes, as shown in the following screen capture.

enter image description here

+1


source







All Articles