user1934428
user1934428

Reputation: 22301

What exactly is flushed by flush/0 in Elixir?

I'm still an absolute newbie in Elixir:

I stumbled over the following example in the documentation or Port objects:

port = Port.open({:spawn, "cat"}, [:binary])
send(port, {self(), {:command, "hello"}})
send(port, {self(), {:command, "world"}})
flush() 

How does flush() know, what it should flush? If there would be a port.flush(), I would find it more understandable.

I tried to search the Elixir docs for a documentation for the flush function, but I only found StringIO.flush.

There does not seem to be a Kernel.flush either; at least it's not listed in https://hexdocs.pm/elixir/1.14.5/Kernel.html .

I would appreciate any pointer of where this function is defined. Also, any suggestion on how to search the online docs of Elixir better, would be highly appreciated.

Upvotes: 1

Views: 373

Answers (2)

bortzmeyer
bortzmeyer

Reputation: 35519

For use under Iex, see Daniel's reply. For using in a standalone Elixir program, just read the messages from cat with receive (output from the program you spawn are simply regular Elixir messages for the Elixir process):

port = Port.open({:spawn, "cat"}, [:binary])
send(port, {self(), {:command, "hello"}})
send(port, {self(), {:command, "world"}})
receive do
  {_, {:data, msg}} -> IO.puts(msg)
end
send(port, {self(), :close})

Upvotes: 1

Daniel
Daniel

Reputation: 2554

flush/0 is a utility function from IEx, located in IEx.Helpers. You don't need to specify the module name from an iex session because it will be imported automatically. It does exactly what it says in the documentation:

Clears out all messages sent to the shell's inbox and prints them out.

As for searching for documentation, this one is special this is why it was hard to find, otherwise you should have zero problems in the future.

Upvotes: 3

Related Questions