2016-12-07 13 views
2

외부 프로세스의 표준 입력에 쓸 수 있습니까? NIF가 유일한 옵션입니까?엘릭서에서 외부 프로세스의 표준 입력에 쓰는 방법

엘릭서, 블록에서 시작하고 사용자 입력을 기다리는 과정 :

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 
입니다
+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 stdin에 쓰려면 반대쪽을 찾고 있습니다. – LemmonMaxwell

답변

4

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