Erlang – OTP


Erlang – OTP


”;


OTP stands for Open Telecom Platform. It’s an application operating system and a set of libraries and procedures used for building large-scale, fault-tolerant, distributed applications. If you want to program your own applications using OTP, then the central concept that you will find very useful is the OTP behavior. A behavior encapsulates common behavioral patterns — think of it as an application framework that is parameterized by a callback module.

The power of OTP comes from the properties such as fault tolerance, scalability, dynamic-code upgrade, and so on, can be provided by the behavior itself. So the first basic concept is to create a server component that mimics the basics of an OTP environment, let’s look at the following example for the same.

Example

-module(server). 
-export([start/2, rpc/2]). 

start(Name, Mod) -> 
   register(Name, spawn(fun() -> loop(Name, Mod, Mod:init()) end)). 
rpc(Name, Request) -> 
   Name ! {self(), Request}, 
   receive 
      {Name, Response} -> Response 
   end. 
   
loop(Name, Mod, State) ->
   receive 
      {From, Request} ->
         {Response, State1} = Mod:handle(Request, State), 
         From ! {Name, Response}, 
         loop(Name, Mod, State1) 
   end.

The following things need to be noted about the above program −

  • The process if registered with the system using the register function.

  • The process spawns a loop function which handles the processing.

Now let’s write a client program that will utilize the server program.

Example

-module(name_server). 
-export([init/0, add/2, whereis/1, handle/2]). 
-import(server1, [rpc/2]). 

add(Name, Place) -> rpc(name_server, {add, Name, Place}). 
whereis(Name) -> rpc(name_server, {whereis, Name}). 

init() -> dict:new().
handle({add, Name, Place}, Dict) -> {ok, dict:store(Name, Place, Dict)}; 
handle({whereis, Name}, Dict) -> {dict:find(Name, Dict), Dict}.

This code actually performs two tasks. It serves as a callback module that is called from the server framework code, and at the same time, it contains the interfacing routines that will be called by the client. The usual OTP convention is to combine both functions in the same module.

So here is how the above program needs to be run −

In erl, first run the server program by running the following command.

server(name_server,name_server)

You will get the following output −

Output

true

Then, run the following command

name_server.add(erlang,”Tutorialspoint”).

You will get the following output −

Output

Ok

Then, run the following command −

name_server.whereis(erlang).

You will get the following output −

Output

{ok,"Tutorialspoint"}

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *