akonsu
akonsu

Reputation: 29536

avoid crashing when sending message to non-existent process

In the code below, if ! call fails then my program crashes. I would like to return, say, {no_process, "some_process"} instead of crashing. How to achieve this? (I know it is a trivial question for an experienced Erlang developer, which I am not yet...)

test() ->
    some_process ! {test},
    ok.

Upvotes: 1

Views: 371

Answers (3)

Pascal
Pascal

Reputation: 14042

If you use pid rather than registered name, it won't fail.

Generally the registered process are monitored in a supervision tree, and each supervisor is in charge of the start and restart policy of its children. For short living process, it is better to avoid name registration.

Upvotes: 0

Dmitry Belyaev
Dmitry Belyaev

Reputation: 2593

Note that this error happens only if you use atom instead of a process identifier. So you can try to find pid of the desired process using erlang:whereis/1 and if you get undefined you know that name is not registered and you can return you {no_process, ProcessName}, otherwise send the message to the Pid you got. Something like this:

send_msg(Name, Msg) when is_atom(Name) ->
   case erlang:whereis(Name) of
      undefined -> {no_process, Name};
      Pid -> Pid ! Msg
   end;
send_msg(PidOrTuple, Msg) ->
   PidOrTuple ! Msg.

Upvotes: 3

Danil Onishchenko
Danil Onishchenko

Reputation: 2040

Just trap an exception which occurs when you are sending a message to a process which doesn't exists. This is an example of function doing that:

send_msg(Process, Msg) ->
    try
        Process ! Msg,
        ok
    catch
        error:badarg -> {no_process, Process}
    end.

To send your message just call:

send_msg(some_process, Msg).

Upvotes: 3

Related Questions