Write an Elixir logic using Process.monitor to detect when a dependent service process…
- User
Write an Elixir logic using
Process.monitorto detect when a dependent service process dies without crashing the caller. Assistant
Write an Elixir logic using Process.monitor to detect when a dependent service process dies without crashing the caller.
1. Understand the Goal: The user wants Elixir code demonstrating Process.monitor. The specific use case is to detect when a "dependent service process" (another process) dies without the monitoring process (the caller) crashing. This implies an asynchronous, "fire-and-forget" monitoring pattern, unlike Process.link which would crash both.
Identify Key Concepts:
Process.monitor/1: This function creates a link from the caller to the target PID. Crucially, this link is one-way (asymmetric) and results in a message {:DOWN, ref, :process, pid, reason} being sent to the caller when the target dies. It does not crash the caller.GenServer or a simple spawn loop). A GenServer is the standard Elixir way to structure long-running processes.Determine the Best Approach for the Example:
spawn + receive loop. Good for understanding the basics, but less idiomatic for production code.GenServer. This is the standard OTP way. It shows how to handle the :DOWN message in handle_info. It's robust and demonstrates "best practices."Decision: I will provide a GenServer example because it's how Elixir developers actually write services. I'll also briefly explain the raw concept if needed, but the code should be GenServer-centric.
Drafting the Code Structure (Mental Draft):
ServiceMonitor (or similar).ref) and maybe the PID.monitor_service/1 function: Takes a PID, calls Process.monitor, saves the ref.handle_info/2: This is where the magic happens. Match on {:DOWN, ...}.handle_info: Log the error, maybe restart the service (out of scope, but good to mention), or just update state.Refining the Logic:
Writing the Elixir Code (Iterative refinement):
defmodule MonitorExample do
use GenServer
# Client API
def start_link(_) do
GenServer.start_link(__MODULE__, [], name: __MODULE__)
end
def watch(pid) do
GenServer.cast(__MODULE__, {:watch, pid})
end
# Server Callbacks
def init(_) do
{:ok, %{monitors: %{}}}
end
def handle_cast({:watch, pid}, state) do
ref = Process.monitor(pid)
# Store ref to pid mapping if we need to know *what* died later easily
new_state = Map.put(state, ref, pid)
{:noreply, new_state}
end
def handle_info({:DOWN, ref, :process, pid, reason}, state) do
IO.puts "Process #{inspect pid} died! Reason: #{inspect reason}"
# Clean up state
new_state = Map.delete(state, ref)
{:noreply, new_state}
end
end
Adding Explanations:
Process.monitor is the right tool (vs link).{:DOWN, ...}.handle_info (crucial for receiving raw messages in GenServers).Creating a "Runnable Script":
To make the answer useful, I should provide a script that the user can copy-paste into an .exs file and run. This script needs to:
Reviewing the constraints:
:DOWN.monitor sends a message, it doesn't propagate the exit signal.Final Polish: Ensure the code is clean, comments are helpful, and the distinction between monitor and link is clear. (Self-correction: Make sure to demonitor if the monitor process stops watching intentionally, though not strictly required for the basic example, it's good hygiene. I'll stick to the simplest working example to not overcomplicate).
Wait, should I handle the case where the process is already dead? Process.monitor handles this immediately by sending the :DOWN message right away. I should mention this "race condition" safety feature.
Constructing the Output:
GenServer as the idiomatic context.Process.monitor, handle_info, and the :DOWN message.This thought process moves from understanding the core requirement -> selecting the right tool (GenServer) -> implementing the logic -> creating a usage scenario -> refining the explanation.
Here is an example of how to implement this using a GenServer.
The key difference between Process.link and Process.monitor is that links are bidirectional and crash connected processes, while monitors are unidirectional and send a message to the observer when the target dies.
In this example, the MonitorService spawns a child process (the dependent service) and sets up a monitor. When the child crashes, the parent receives a message in handle_info without crashing itself.
defmodule MonitorService do
use GenServer
# --- Client API ---
def start_link(_) do
GenServer.start_link(__MODULE__, [], name: __MODULE__)
end
# --- Server Callbacks ---
@impl true
def init(_) do
# We start a dependent process (simulating a DB connection or external service)
# We trap exits specifically to demonstrate that links would crash us,
# but monitors won't.
Process.flag(:trap_exit, true)
pid = spawn_dependent_service()
# 1. Setup the monitor
# This returns a reference we can use to stop monitoring later.
ref = Process.monitor(pid)
{:ok, %{dependent_pid: pid, monitor_ref: ref}}
end
@impl true
def handle_info({:DOWN, ref, :process, pid, reason}, state) do
# 2. Handle the death
# This clause is triggered when the monitored process dies.
# The parent process (this GenServer) continues running.
IO.puts("[MonitorService] Detected crash!")
IO.puts(" PID: #{inspect(pid)}")
IO.puts(" Reference: #{inspect(ref)}")
IO.puts(" Reason: #{inspect(reason)}")
# Logic to restart the service or switch to a fallback mode goes here
new_pid = spawn_dependent_service()
new_ref = Process.monitor(new_pid)
{:noreply, %{dependent_pid: new_pid, monitor_ref: new_ref}}
end
@impl true
def handle_info(msg, state) do
# Catch-all for other messages
IO.puts("Received unexpected message: #{inspect(msg)}")
{:noreply, state}
end
# --- Private Helpers ---
defp spawn_dependent_service do
spawn(fn ->
IO.puts("[DependentService] Started.")
# Simulate work
Process.sleep(2000)
# Simulate a crash
raise "Something went wrong in the dependent service!"
end)
end
end
iex -sMonitorService.start_link([])Output flow:
[DependentService] starts.[MonitorService] immediately prints the "Detected crash!" message.MonitorService process remains alive (you can verify this by running Process.alive?(pid) or checking :observer.start).Process.monitor(pid):
This creates a unidirectional link. If the monitored process dies, the monitor is removed automatically, and a message is sent to the caller.
The :DOWN Message:
When a monitored process terminates, the monitoring process receives a tuple in this format:
{:DOWN, ref, :process, pid, reason}
ref: The monitor reference returned by Process.monitor.reason: Why it died (e.g., :normal, :killed, or {:EXIT, "Error message"}).handle_info/2:
Since the monitor sends a plain Erlang term message, it is handled inside handle_info within a GenServer, rather than a standard GenServer call/cast callback.