Search code examples
elixirport

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.


Solution

  • 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})