Lem*_*ell 2 unix erlang pipe elixir mkfifo
是否有可能在Elixir中写入外部进程的标准输入?NIF现在是唯一的选择吗?
从Elixir开始,阻止并等待用户输入的过程:
pid = spawn(fn ->
System.cmd("sh", [
Path.join([System.cwd, "sh", "wait_for_input"]),
"Hello world"
])
end)
Run Code Online (Sandbox Code Playgroud)
我想实现这样的目标
IO.write pid, "Hello"
IO.write pid, "Hello again"
Run Code Online (Sandbox Code Playgroud)
这是剧本
#!/bin/sh
while read data
do
echo $data >> file_output.txt
done
Run Code Online (Sandbox Code Playgroud)
你可以用Port
它.请注意,read
内置文件sh
只会在发送换行符时获取数据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
Run Code Online (Sandbox Code Playgroud)