Astarno
Inspect the environment of a Process
What would be the correct approach to inspect the current environment of a Process? For example, if I would have a simple Process defined as below:
defmodule Stack do
def loop(state, ctr) do
receive do
{_from, :push, value} ->
loop([value | state], ctr + 1)
{from, :pop} ->
[h | t] = state
send(from, {:reply, h})
loop(t, ctr)
end
loop(state)
end
end
Here the environment consists of two variables (parameters of the loop function) at any point during execution. How could I easily get a list of such variables and their associated value as such:
state: value
ctr: value
I’m new to Elixir. Thanks in advance!
Most Liked
lucaong
When implementing something similar with a GenServer one can use :sys.get_state(pid) for debugging, but in this case I don’t see a way without modifying the code. In your example the state is the arguments of the recursive call to loop, so one needs to tap into the function to inspect the state.
What’s your use case?
lucaong
Hi @Astarno,
In your example, you could add a receive clause to return the state:
defmodule Stack do
def loop(state, ctr) do
receive do
{_from, :push, value} ->
loop([value | state], ctr + 1)
{from, :pop} ->
[h | t] = state
send(from, {:reply, h})
loop(t, ctr)
{from, :inspect} ->
send(from, {state, ctr})
loop(state, ctr)
end
end
end
Now you can send a message like {self(), :inspect} and receive the state as a message:
iex(1)> pid = spawn(Stack, :loop, [[], 0])
#PID<0.127.0>
iex(2)> send(pid, {self, :inspect})
{#PID<0.105.0>, :inspect}
iex(3)> flush
{[], 0}
:ok
iex(4)> send(pid, {self, :push, "foo"})
{#PID<0.105.0>, :push, "foo"}
iex(5)> flush
:ok
iex(6)> send(pid, {self, :inspect})
{#PID<0.105.0>, :inspect}
iex(7)> flush
{["foo"], 1}
:ok
RudManusachi
In general the better practice would be to use built in OTP abstractions like GenServer, as @lucaong mentioned, rather than plain loop with receive do, and we can use :sys.get_state, :sys.replace_state, :observer and other tools to inspect running system in realtime without changing the code of the project.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








