Hi elixirians,
Here I am trying to monitor the process. Based on the official documentation I just tried with the follwing lines of code.
However the monitoring callback is not triggerd. Please help me to figure out this.
defmodule HelloServer do
use GenServer
## Client API
def start do
GenServer.start_link(__MODULE__,1, [])
end
def add pid,value do
GenServer.call(pid,{:add,value})
end
def get pid do
GenServer.call(pid,:get)
end
def reset pid do
GenServer.cast(pid, :reset)
end
def monitor pid do
GenServer.cast(pid, {:monitor, pid})
end
def stop pid do
Agent.stop(pid)
end
## Server API
def init(initial_value) do # initiating the state with the value 1 passed
{:ok,initial_value}
end
# add the value to the state and returns :ok
def handle_call({:add,value},_from,state) do
{:reply, :ok,state + value}
end
# returns the state to the caller
def handle_call(:get,_from,state) do
{:reply,state,state}
end
# just reset the state to value 1
def handle_cast(:reset,state) do
IO.puts "value has been reset "
{:noreply,1}
end
# monitor the given process id
def handle_cast({:monitor, pid},state) do
IO.puts "monitoring the process"
Process.monitor pid
{:noreply,1}
end
# This executes periodically
def handle_info(:work,state) do
IO.puts " This message prints every after 3 seconds"
schedule_work()
{:noreply,state}
end
# this is triggered when the agent stopped the process
def handle_info({:DOWN, ref, :process, _pid, _reason},state) do
IO.puts "Agent stopped the pid"
{:noreply, state}
end
#catch-all clause for the handle_info for handling unkown messages
def handle_info(_msg, state) do
IO.puts "unknown message"
{:noreply, state}
end
defp schedule_work() do
Process.send_after(self(), :work, 2 * 1000) # In 2 seconds
end
end
This is How I am using the file in iex
iex> {:ok, pid} = HelloServer.start
iex> HelloServer.monitor pid
iex> HelloServer.stop pid
# after calling this it should trigger the handle_info :DOWN ...
# but unfortunately not able to trigger that..
# am I missing something here ?
Thanks in advance.