I'm new to elixir, experimenting around in iex
shell to learn, and I have be a noob question.
For simplicity let's call the current shell session process the "main process".
I spawn a child process, write a receive
block in "main process" to listen for child message. When hit enter, it'll put the "main process" into a waiting
status. This basically freezes the "main process", making it irresponsive to further input.
Many times I got stuck in this status by mistake. If I mess up I need to shutdown the shell and start over again, losing all the states and setups.
My question : is there a way to withdraw/invalidate/break out of a working receive
block?
Or maybe is there a way that I can start another session, without killing the previous one, then send some message to it to unfreeze it?
I don't think you can interrupt receive
, you could kill the process using its PID from another process or set a timeout
to it, then you get back the control of the session if nothing was received between this timeout window.
receive do
a -> a
after
1_000 -> "nothing after 1s"
end
take a look at https://elixir-lang.org/getting-started/processes.html#send-and-receive
Taking the second approach will require a bit of work. Each iex
instance is a separate OTP node, so in order to make those two talk to each other, you'll need to do the following:
iex --cookie foo --name "node1@127.0.0.1"
iex --cookie foo --name "node2@127.0.0.1"
node1
)::global.register_name(:node1, self())
node1
):Node.connect(:"node2@127.0.0.1")
Now, you can start listening for messages in node1
with receive
. To send a message from node2 to node1, find out its PID within the cluster and dispatch the message there:
:global.whereis_name(:node1) |> send "Hello!"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.