sign in
Home | Updates | Pages | Users | Admin | Help
Comparing version 3 and version 2 back

h1. Erlang Study - Robustness (part3)

* Origin: "Getting Started With Erlang":http://erlang.org/doc/doc-5.5.2/doc/getting_started/part_frame.html
* See also: 
** [[erlangstudy|Erlang Study - Sequential Programming (part1)]]
** [[erlangstudy2|Erlang Study - Concurrent Programming (part2)]]
** [[erlangstudy4|Erlang Study - System Principles (part4)]]

h2. 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.* h2. 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* .
Powered by JunebugWiki v0.0.31