Matthias
Matthias

Reputation: 4677

Reusing a process' mailbox in Erlang

If an Erlang process proc1 is killed (exit(killed)) and another process proc2 is notified of this event because it's linked to the process proc1, is there a possibility to respawn a replacement process with the mailbox of the killed process proc1?

Upvotes: 2

Views: 339

Answers (1)

mpm
mpm

Reputation: 3584

Not really. Processes don't share any data, so when one dies no other can access any of it's memory. Erlang would not know how long to wait to garbage-collect such mailbox.

You could simulate that with separate proxy process that just keeps track of mailbox.

Or you could try to handle little better being killed in proc1. You could use process_flag(trap_exit, true) which would allow you to receive exit(killed) message as normal message {'EXIT',FromPid,killed}. And when you receive you read you whole mailbox, and then continue exiting with all messages being part of exit reason.

It could look somewhat like this:

init(Args) ->
   process_flag(trap_exit, true),
   .... % continiue process innicializaiton.

loop(State) ->
  receive 
   .... 
    {'EXIT', _FromPid, killed} ->
        exit({killed, all_messages()})
  end.


all_messages() ->
   all_messages([]).

all_messages(Messages) ->
     receive 
        AnyMessage ->
            all_messages( [AnyMessage|Messages])
     after 0 ->
            lists:reverse(Messages)
     end.

And proc2 would receive all unprocessed messages, and could send them again to newly spawn process.

Upvotes: 4

Related Questions