🎓 A1Learner
🔍
0 of 46 lessons completed

Elixir Process Info

Process info is a report about a running process. It answers questions about that process, like how many messages wait for it.

A process starts with an empty mailbox

The current process has no waiting messages. Its status is running.

IO.inspect(Process.info(self(), :message_queue_len))
IO.inspect(Process.info(self(), :status))

Several fields come back in one call

One call can ask for several fields at once. The answer keeps the order asked for.

IO.inspect(Process.info(self(), [:message_queue_len, :status, :trap_exit]))

Waiting messages are counted before they are read

A waiting worker keeps its job messages unread until it gets its stop message. The count shows three waiting messages.

parent = self()
worker = spawn(fn ->
  send(parent, :ready)
  receive do
    :stop -> :ok
  end
end)
receive do
  :ready -> :ok
end
send(worker, {:job, 1})
send(worker, {:job, 2})
send(worker, {:job, 3})
IO.inspect(Process.info(worker, :message_queue_len))
IO.inspect(Process.alive?(worker))
ref = Process.monitor(worker)
send(worker, :stop)
receive do
  {:DOWN, ^ref, :process, ^worker, :normal} -> :ok
end
IO.inspect(Process.alive?(worker))

Example

parent = self()
worker = spawn(fn ->
  send(parent, :ready)
  receive do
    :stop -> :ok
  end
end)
receive do
  :ready -> :ok
end
send(worker, {:job, 1})
send(worker, {:job, 2})
IO.inspect(Process.info(worker, :message_queue_len))
IO.inspect(Process.info(self(), :message_queue_len))
IO.inspect(Process.info(self(), :status))
IO.inspect(Process.alive?(worker))
ref = Process.monitor(worker)
send(worker, :stop)
receive do
  {:DOWN, ^ref, :process, ^worker, :normal} -> :ok
end
IO.inspect(Process.alive?(worker))

Key points

  • Report: Process.info returns facts about one process at a time.
  • Queue length: the message queue length field counts messages waiting for a process.
  • Status: the status field tells whether a process is running or waiting.
  • Trap flag: the trap exit field tells whether a process traps exit signals.
  • Alive check: Process.alive? returns true while a process still runs.
  • Use Process.info to inspect a process without changing its state.

In this example, a waiting worker is started, then it receives two job messages, then its queue length is printed, then the current process queue length and status are printed, then the worker is shown alive, then the worker is stopped, and finally the worker is shown no longer alive.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A worker has two unread job messages. What does Process.info for its queue length return?