Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 746
Opentuned Avatar asked Dec 01 '14 19:12

Opentuned


People also ask

How do I send a message to Erlang?

Erlang uses the exclamation mark (!) as the operator for sending a message. Example: As I have mentioned before, the shell is nothing more than a process.

Which module is used to spawn processes manually in Erlang?

spawn() creates a new process and returns the pid. The new process starts executing in Module:Name(Arg1,...,ArgN) where the arguments are the elements of the (possible empty) Args argument list.

Is process alive Erlang?

This is called as is_process_alive(Pid). A Pid must refer to a process at the local node. It returns true if the process exists and is alive i.e., whether it is not exiting and has not exited. Otherwise, returns false.

How do I terminate a process in Erlang?

A process can terminate itself by calling one of the BIFs exit(Reason), erlang:error(Reason), erlang:error(Reason, Args), erlang:fault(Reason) or erlang:fault(Reason, Args). The process then terminates with reason Reason for exit/1 or {Reason,Stack} for the others.


1 Answers

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.
like image 99
zxq9 Avatar answered Sep 24 '22 18:09

zxq9