Saturday, April 19, 2008

A little of Erlang

I have started doing some toy programs with Erlang. That is a functional, dynamically typed language that provides support for implementing parallel and distributed systems. It is very simple to write a small distributed application running on the same machine; however, I had problems to find information about this on the web. Thus, I decided to write this little tutorial which uses examples from the book Concurrent Programming in Erlang by Joe Armstrong.

This is the code of a server application, that allows users to make deposits, withdraws and enquires. The client application is given here. I tested these programs in a CentOS linux kernel 2.6.18-53.1.14.el5 running on a 64 bit Intel(R) Xeon(R) CPU. My interpreter is Erlang (BEAM) emulator version 5.5.2 [source] [64-bit] [async-threads:0].

To run these examples, open two command shells, that I shall call server shell and client shell. In the server shell, change to the directory that contains bank_server and start the erlang prompt:

erl -sname bank

Once in the erlang prompt, type the following commands:

c(bank_server.erl).
bank_server:start().

Likewise, start the command prompt in the client shell:

erl

In order to test if the server is reachable, in the client shell you can ping the server erlang node:

net:ping(bank@Tuvalu).

If you get pong as answer, then everything is fine. But, if there is any error, you will get the atom pang instead. I really think this is a bad interface for reporting errors, but, Alas, it is not my decision... Anyway, here, Tuvalu is the short name of the machine where I was running this example, and bank is the node name, determined in the command prompt when starting erlang in the server shell. Once in the erlang prompt, one can access the bank server using the interface provided by the client application. A simple example section is:

bank_client:deposit(fernando, 100).
bank_client:ask(fernando).
bank_client:withdraw(fernando, 50).
bank_client:ask(fernando).

1 Comments:

Blogger Ulf Wiger said...

In a real production system, you might e.g. use the 'distributed' parameter in the OTP kernel application. There, you can tell the net_kernel to wait for a set of nodes, either forever, or for a certain period of time. The application controller can then start applications on the available nodes according to a predefined pattern.

The net:ping/1 function is mainly used when testing stuff from the shell.

11:01 AM  

Post a Comment

<< Home