【问题标题】:How to write to stdin of external process in Elixir如何在 Elixir 中写入外部进程的标准输入
【发布时间】:2017-04-22 21:14:21
【问题描述】:

是否可以在 Elixir 中写入外部进程的标准输入? NIF 是目前唯一的选择吗?

从 Elixir 开始的进程,阻塞并等待用户输入:

pid = spawn(fn ->
   System.cmd("sh", [
    Path.join([System.cwd, "sh", "wait_for_input"]),
   "Hello world"
  ])
end)

我想实现这样的目标

IO.write pid, "Hello"
IO.write pid, "Hello again"

这是脚本

#!/bin/sh
while read data
do
  echo $data >> file_output.txt
done

【问题讨论】:

  • 查看端口:elixir-lang.org/docs/stable/elixir/Port.html。具体来说,Port.open/2Port.command/3
  • @Stratus3D 我正在寻找相反的东西,写入标准输入。
  • @Dogbert 当我运行它发送数据的命令时,但我没有看到它写入外部进程的标准输入。
  • @LemmonMaxwell 您能否发布您使用sh 执行的脚本的简化版本并将数据写入其中以便我可以重现错误? Port.command 应该可以工作:iex(1)> port = Port.open({:spawn, "sh"}, []); Port.command(port, "echo 1\n"); iex(2)> flush {#Port<0.1348>, {:data, '1\n'}}

标签: unix erlang pipe elixir mkfifo


【解决方案1】:

您可以为此使用Port。请注意,shread 内置函数只会在换行符发送到 sh 时获取数据,因此您需要在要将缓冲数据发送到 read 时添加。

$ cat wait_for_input
while read data
do
  echo $data >> file_output.txt
done
$ iex
iex(1)> port = Port.open({:spawn, "sh wait_for_input"}, [])
#Port<0.1260>
iex(2)> Port.command port, "foo\n"
true
iex(3)> Port.command port, "bar\n"
true
iex(4)> Port.close(port)
true
$ cat file_output.txt
foo
bar

【讨论】:

    猜你喜欢
    • 2012-01-18
    • 2012-09-18
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    相关资源
    最近更新 更多