English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

OTP in Erlang

OTP is the abbreviation for Open Telecom Platform. It is an application operating system, as well as a set of libraries and processes for building large-scale, fault-tolerant, and distributed applications. If you want to use OTP Write your own program, and you will find that OTP behavior is a very useful core concept. Behavior encapsulates common behavior patterns - it can be regarded as an application framework parameterized by callback module parameters.

The powerful features of OTP come from its fault tolerance, scalability, and dynamic code upgrade, among other features, which can be provided by the behavior itself. Therefore, the first basic concept is to create a server component that mimics the basic environment of OTP, let's look at the same example below.

Online 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.

For the above program, the following points should be noted:

  • Using the register function to register the process with the system.

  • This process generates a loop function to handle the process itself.

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

Online 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 acts as a callback module called from the server framework code, and at the same time, it contains interface routines that will be called by the client. OTP conventionally combines two functions in the same module.

So this is the way the program above needs to be run-

InerlIn, first run the following command to run the server program.

server(name_server,name_server)

You will get the following output-

Output Result

true

Then, run the following command

name_server.add(erlang,”w3codebox).

You will get the following output-

Output Result

Ok

Then, run the following command-

name_server.whereis(erlang).

You will get the following output-

Output Result

{ok,"w3codebox"}