Skip to content

Instantly share code, notes, and snippets.

@binarytemple
Last active February 1, 2022 20:48
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save binarytemple/9ebc267bf01cab86e8fbc9188e6a10d1 to your computer and use it in GitHub Desktop.
Save binarytemple/9ebc267bf01cab86e8fbc9188e6a10d1 to your computer and use it in GitHub Desktop.
Generate a list of all processes in the system which are neither linked nor monitored.

Inspired by Stuff Goes Bad - Erlang in Anger

Is the global process count indicative of a leak? If so, you may need to investigate unlinked processes, or peek inside supervisors’ children lists to see what may be weird-looking.

defmodule Diags do 

  @doc """
  Generate a list of all processes in the system which are neither linked nor monitored.
  """
  def list_non_linked_non_monitored_processes do 
        Process.list |> 
    Enum.map( fn pid -> {pid, Process.info( pid, [:links,:monitors,:registered_name])}  end) |> 
    Enum.map(
      fn {pid, words} -> {pid,
        Keyword.get(words,:links),
        Keyword.get(words,:monitors),
        Keyword.get(words,:registered_name)
      }
    end ) |>
    Enum.filter(fn 
      {_,[],[],_} -> true
      _  -> false
    end)
  end
  
  @doc """
  Simplified version of the above function
  """
  def list_non_linked_non_monitored_processes_simplified do 
    for pid <- Process.list, 
      pi <- [ Process.info(pid, [:links,:monitors,:registered_name]) ],
      [links: [], monitors: [], registered_name: registered_name ] <- [pi],
      do: {pid, registered_name}
  end
end
iex(153)> idler = fn -> receive do x -> IO.puts("#{inspect x}") end end
#Function<20.50752066/0 in :erl_eval.expr/5>

iex(154)> Diags.list_non_linked_non_monitored_processes
[{#PID<0.130.0>, [], [], []}]

iex(155)> spawn(idler)
#PID<0.1029.0>
iex(156)> spawn(idler)                                 
#PID<0.1031.0>

iex(157)> Diags.list_non_linked_non_monitored_processes
[{#PID<0.130.0>, [], [], []}, {#PID<0.1029.0>, [], [], []},
 {#PID<0.1031.0>, [], [], []}]

Update - simplified the original function list_non_linked_non_monitored_processes/0

iex(190)> Diags.list_non_linked_non_monitored_processes
[{#PID<0.130.0>, []}, {#PID<0.1029.0>, []}, {#PID<0.1031.0>, []}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment