2016-12-07 42 views
2

是否可以在Elixir中写入外部进程的stdin? NIF是目前唯一的选择吗?如何在Elixir中写入外部进程的stdin

,从药剂,块开始,等待用户输入的过程:

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

我想实现这样的事情

​​3210

这是脚本

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

查看端口:http://elixir-lang.org/docs/stable/elixir/Port.html。特别是,'Port.open/2'和'Port.command/3'。 – Dogbert

+0

这似乎也是相关的:https://stackoverflow.com/questions/10872909/erlang-read-stdin-write-stdout – Stratus3D

+0

@ Stratus3D我正在寻找相反的,写入标准输入。 – LemmonMaxwell

回答

4

您可以使用Port。请注意,sh内置的read内置函数仅在发送换行符为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