2 3 4 5 6 7

Messages

30

To send a message to another Erlang process you should use ! operator. You write it like that: a process identifier, an exclamation mark, and then the message itself:

Proc = spawn(world, loop),

% ...

Proc ! "Hello".

To receive a message you use receive statement:

loop() ->
    receive
        Message ->
            io:format("Message received: ~s~n", [Messsage])
    end.

You can specify a timeout and handle the case when no messages were received within a given period of time:

loop() ->
    receive
        Message ->
            io:format("Message received: ~s~n", [Messsage]),

        after 5000 ->
            io:format("5 seconds have passed, but no messages have been received~n")
    end.

Now we can implement an event loop on top of messaging.

Rate this post:
Lesson 6
Share this page:

Learning plan

The most simple Erlang program to start with
How you write loops in Erlang and other functional programming languages
What is Erlang process and how to spawn it
5. Messages
How to communicate between Erlang processes with messages
How to organize top-level event loop in your program
7. Records
How to define your own data types with named fields