erlangstudy3
Erlang Study – Robustness (part3)
- Origin: Getting Started With Erlang
- See also:
Timeouts
One way to let a function to finish, is to make it exit if it does not receive a message from ping within a certain time . This can be done by adding a timeout to the function as shown in the following example:
pong() ->
receive
{ping, Ping_PID} ->
io:format("Pong received ping~n", []),
Ping_PID ! pong,
pong()
after 5000 ->
io:format("Pong timed out~n", [])
end.
We start the timeout ( after 5000 ) when we enter receive. The timeout is canceled if {ping,Ping_PID} is received.
If {ping,Ping_PID} is not received, the actions following the timeout will be done after 5000 milliseconds.
after must be last in the receive, i.e. preceded by all other message reception specifications in the receive.
In general, there are better ways than using timeouts to supervise parts of a distributed Erlang system. Timeouts are usually appropriate to supervise external events, for example if you have expected a message from some external system within a specified time.
Error Handling
- A process which executes exit(normal) or simply runs out of things to do has a normal exit.
- A process which encounters a runtime error (e.g. divide by zero, bad match, trying to call a function which doesn’t exist etc) exits with an error, i.e. has an abnormal exit.
- A process which executes exit(Reason) where Reason is any Erlang term except the atom normal, also has an abnormal exit .
If a process calls link(Other_Pid) it sets up a bidirectional link between itself and the process called Other_Pid . When a process terminates its sends something called a signal to all the processes it has links to. The signal carries information about the pid it was sent from and the exit reason .
- process which receives a normal exit—ignore the signal
- process which receives an abnormal exit—bypass all messages to the receiving process and to kill it and to propagate the same error signal to the killed process’ links
As we often want to create a process and link to it at the same time, there is a special BIF, spawn_link which does the same as spawn , but also creates a link to the spawned process .