DEV Community 👩‍💻👨‍💻


Posted on

Processes in Elixir


The basic mechanism for spawning new processes is the auto-imported spawn/1 function:

iex> spawn(fn -> 1 + 2 end)
# PID<0.43.0>

Notice spawn/1 returns a PID (process identifier). At this point, the process you spawned is very likely dead. The spawned process will execute the given function and exit after the function is done:

Can we see if its dead or alive

iex> pid = spawn(fn -> 1 + 2 end)
iex> Process.alive?(pid)
Enter fullscreen mode Exit fullscreen mode
Lets send a Message from one process to another

We can retrieve the PID of the current process by calling self :

iex(6)> parent=self()
Enter fullscreen mode Exit fullscreen mode


iex(7)> spawn(fn->send(parent,{:hello,self()}) end) 
Enter fullscreen mode Exit fullscreen mode

When a message is sent to a process, the message is stored in the process mailbox. The receive/1 block goes through the current process mailbox searching for a message that matches any of the given patterns


iex(8)> receive do                                      
...(8)> {:hello,pid}->"Got hello form #{inspect pid}"  
...(8)> end                                               
"Got hello form #PID<0.115.0>"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

50 CLI Tools You Can't Live Without

The top 50 must-have CLI tools, including some scripts to help you automate the installation and updating of these tools on various systems/distros.