Archive

Posts Tagged ‘pid’

Something maybe you don’t know about Erlang PIDs

August 30, 2010 Leave a comment

A pid or process identifier, is a data  type used to identify a process. Usually they are generated from one of the functions used to create a new process  (e.g. spawn/spawn_link) and bounded to a variable.

When I started with Erlang I had huge problems with supervisors and trap exits, but pids helped me quite a lot during my tests.

Let’s get a pid in order to analyse its structure; the easiest way consists in the use of the bif self() that returns the pid of the calling process:

1> self().
<0.32.0>

A pid is thus something like:  < A.B.C > where:

  1. A represents the node node id where the process “lives”. It may be 0 if the node is local, or another number if the node is remote. The numberh is not random: it is nothing more than the internal index for that node in dist_entry.
  2. B represents the process itself, an index into the process table proc_tab. (15 bits)
  3. C represents a serial that is increased every time MAXPROCS has been reached (3 bits)

If you know the name of one of your registered process you may want to send it some value, and this is pretty easy if you bounded your pid to a variable after a spawn/N or self/0 :

2> A = self().
<0.32.0>
3> A ! hello.
hello
4> flush().
Shell got hello
ok

If you didn’t bind the variable but you registered the process, you can retrieve the pid and bind it as follows:

7> A1 = whereis(proc_registration_name).
<0.24.0>

And if you want to build a pid by a series of 3 numbers? Well, in that case you could build the pid in one of the following ways:

8> Pid = "<0.24.0>".
9> A2 = list_to_pid(Pid).
<0.24.0>

Notice that you can’t do list_to_pid/1 on an external pid (i.e. one that does not start with a 0 if you are a non-distributed node).

Another possibility for you is:

10> pid(0,24,0).
<0.24.0>
Categories: English, Erlang Tags: ,
Follow

Get every new post delivered to your Inbox.

Join 27 other followers