ConnorRigby

ConnorRigby

Nerves Core Team

I have a GenServer that reads/writes to a Linux Pipe or Fifo. I need to do:

{:ok, fifo} = :file.open('/path/to/fifo', [:read, :write, :binary])
{:ok, <<protocol_pattern_match>>} = :file.read(fifo, protocol_size)

Except :file.read/2 blocks the entire calling process until it is complete similar to read() in C. This is fine because i should be able to just do task = Task.async(:file, :read, [protocol_size]) and get the result in
handle_info/2. Maybe i misunderstood the docs, but that doesn’t seem to be working for me. I’m expecting to get handle_info({ref, {:ok, <<protocol_pattern_match>>}, %{task: %{ref: ref}}) but that doesn’t seem to happen.

My other issue is that Task.shutdown/2 or :file.close/1 do not seem to be working as expected.
the docs for Task.shutdown/2 say when a calling process exits, the task should exit, but even using
Task.shutdown(state.task, :brutal_kill) doesn’t allow me to call :file.close(state.fifo) in terminate/2. (It just blocks forever)

anyway here’s the entire GenServer implementation:

defmodule PipeWorker do
  @moduledoc """
  Proxy for IO operations.
  """
  use GenServer
  require Logger

  def start_link(pipe_name) do
    GenServer.start_link(__MODULE__, pipe_name)
  end

  def close(pipe) do
    GenServer.stop(pipe, :normal)
  end

  def read(pipe, size) do
    GenServer.call(pipe, {:read, [size]}, :infinity)
  end

  def write(pipe, packet) do
    GenServer.call(pipe, {:write, [packet]}, :infinity)
  end

  def init(pipe_name) do
    with {_, 0} <- System.cmd("mkfifo", [pipe_name]),
         {:ok, pipe} <- :file.open(to_charlist(pipe_name), [:read, :write, :binary]) do
      {:ok, %{pipe_name: pipe_name, pipe: pipe, task: nil, caller: nil}}
    else
      {:error, _} = error -> {:stop, error}
      {_, _num} -> {:stop, {:error, "mkfifo"}}
    end
  end

  def terminate(_, state) do
    Logger.warn("PipeWorker #{state.pipe_name} exit")
    state.task && Task.shutdown(state.task, :brutal_kill)
    Logger.warn("Pipe Task shut down")
    IO.inspect(state.pipe, label: "pipe")
    # :file.close(state.pipe) # blocks indefinitely no matter what. Shell becomes unresponsive.
    # Logger.warn("Pipe closed")
    File.rm!(state.pipe_name)
    Logger.warn("Pipe removed")
  end

  def handle_call({cmd, args}, {pid, _} = _from, state) do
    IO.inspect([state.pipe | args], label: "Pipe task args")
    task = Task.async(:file, cmd, [state.pipe | args])
    IO.inspect(task, label: "Pipe task")
    {:reply, task.ref, %{state | task: task, caller: pid}}
  end

  # This is never called?
  def handle_info({ref, result}, %{task: %{ref: ref}, caller: pid} = state) do
    IO.inspect({ref, result}, label: "Task result")
    send(pid, {__MODULE__, ref, result})
    {:noreply, %{state | task: nil, caller: nil}}
  end
end

Showing Posts 1 to 10

ConnorRigby

ConnorRigby OP

Nerves Core Team

Okay so while investigating this, i discovered something.

This code will hang forever no matter what. It doesn’t matter how much data
is written to the pipe, the data will never be read by Erlang/Elixir.

{:ok, file} = :file.open(path_to_fifo, [:read, :write, :binary])
{:ok, "hello world"} = :file.read(file, 11)
# in a different tab to `File.write(path_to_fifo, "hello world")`

This code however works fine. I suspect this is because the :raw option is a NIF now. (just a guess?)

# notice the `:raw` option.
{:ok, file} = :file.open(path_to_fifo, [:read, :write, :binary, :raw]) 
{:ok, "hello world"} = :file.read(file, 11)
# in a different tab to `File.write(path_to_fifo, "hello world")`

The only problem with opening in :raw mode is that i can’t use Task to call read/2 because the Task is not an owning process. I get the following error:

** (ErlangError) Erlang error: :not_on_controlling_process
        :prim_file.get_fd_data/1
        :prim_file.read/2
        (elixir) lib/task/supervised.ex:89: Task.Supervised.do_apply/2
        (elixir) lib/task/supervised.ex:38: Task.Supervised.reply/5
        (stdlib) proc_lib.erl:249: :proc_lib.init_p_do_apply/3

I guess this isn’t really an Elixir issue, but an Erlang one but any help would be appreciated.

idi527

idi527

Doesn’t that need to be used with Task.await to receive the result? I also think tasks use receive blocks that wouldn’t work in a genserver process.

ConnorRigby

ConnorRigby OP

Nerves Core Team

From the Task docs:

idi527

idi527

Oh, sorry then.

ConnorRigby

ConnorRigby OP

Nerves Core Team

if i manually change my code to do a :file.read(fd, 0) the behaviour works. I recieve the result in handle_info, so i at least am fairly certain Task is not the problem here.

josevalim

josevalim

Creator of Elixir

The solution is to use ports, which will also give asynchrony. See previous discussion here: Elixir vs Unix named pipe

I think it was recently announced that erlang supports pipes, but I cant recall if in port or file. Or I may be completely misremebering it. Anyway, a port should do nowadays.

ConnorRigby

ConnorRigby OP

Nerves Core Team

Sorry, i should have stated this in the original post, but i have tried this as well and it did not work either.

Interactive Elixir (1.7.3) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> System.cmd("mkfifo", ["/tmp/fifo", "-m", "0666"])          
{"", 0}
iex(2)> port = :erlang.open_port({:spawn, '/tmp/fifo'}, [:binary]) 
#Port<0.7>
iex(3)> sh: /tmp/fifo: Permission denied
                                        sh: line 0: exec: /tmp/fifo: cannot execute: Permission denied

and in another terminal, writing to the FIFO just hangs until i send a ctrl+c

echo "hello world" -e > "/tmp/fifo"                       Thu 24 Jan 2019 10:28:34 AM PST
^CAn error occurred while redirecting file '/tmp/fifo'
open: Interrupted system call
josevalim

josevalim

Creator of Elixir

So this worked:

~/OSS/elixir[jv-basic-releases %]$ mkfifo test.pipe
~/OSS/elixir[jv-basic-releases %]$ erl
Erlang/OTP 21 [erts-10.0] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [hipe]

Eshell V10.0  (abort with ^G)
1> Fifo = open_port("test.pipe", [eof]),
1> receive
1> Msg -> io:format("Got ~p", [Msg])
1> end.
Got {#Port<0.5>,{data,"foo\n"}}ok

After typing the receive, I ran echo "foo" > test.pipe in another terminal. Could it be something related to permissions as the error message says?

ConnorRigby

ConnorRigby OP

Nerves Core Team

ah ha! i was trying to use spawn which was not needed. Will try this method out and report back.

ConnorRigby

ConnorRigby OP

Nerves Core Team

I can confirm that this does in fact allow reading and writing from a named pipe. However it does add the requirement of buffering now, since you are not telling the port how much data you want to read. Either way thanks for the help!

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews