Search code examples
elixirelixir-iex

Elixir IEx shell, how to break out of current `receive` block


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?


Solution

  • 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:

    1. specify the same cookie and a different name for each of them:
    iex --cookie foo --name "[email protected]"
    iex --cookie foo --name "[email protected]"
    
    1. associate a global name with the receiver node (run in node1):
    :global.register_name(:node1, self())
    
    1. connect node1 to node2 (run in node1):
    Node.connect(:"[email protected]")
    

    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!"