5

when you send a message to the shell process, you can flush all messages out by calling: c:flush().

C:\Windows\System32>erl
Eshell V5.9  (abort with ^G)
1> self() ! josh.
josh
2> self() ! me.
me
3> self() ! you.
you
4> flush().
Shell got josh
Shell got me
Shell got you
ok
5>

In my thinking , this empties the mail box of the shell process. What is the equivalent way of emptying the mailbox of any erlang process ?

Jonas
  • 121,568
  • 97
  • 310
  • 388
Muzaaya Joshua
  • 7,736
  • 3
  • 47
  • 86

1 Answers1

9

This function should flush all messages from mailbox (in any process where you call it):

flush() ->
        receive
                _ -> flush()
        after
                0 -> ok
        end.
stemm
  • 5,960
  • 2
  • 34
  • 64
  • Thanks @stemm. I am wondering: `after 0 -> ok ` doesn't it force the process out of the `receive` immediately ? what is your reference for this, please ? – Muzaaya Joshua Aug 16 '12 at 15:20
  • As I understood (and checked in practice) this function would receive all existing messages, while mailbox is not empty. I've read this tip in Francesco Cesarini book Erlang Programming (in 4th paragraph - about parallell programming) – stemm Aug 16 '12 at 15:29
  • 5
    Yes, the `after 0 ->` is guaranteed to try and match through all the messages in the mailbox before it "times out". It is more efficient than doing `after 1 ->` as no timer will actually be started; it is not needed. – rvirding Aug 16 '12 at 17:09