2016-11-21 59 views
2

如何在新進程中讀取stdin?我只能在主流程中放行並打印它。我應該通過get_line控制檯設備還是類似的或不可能的?如何在「不主要」進程中從控制檯讀取

我的代碼:

-module(inputTest). 
-compile([export_all]). 

run() -> 
    Message = io:get_line("[New process] Put sth: "), 
    io:format("[New process] data: ~p~n", [Message]). 


main() -> 
    Message = io:get_line("[Main] Put sth: "), 
    io:format("[Main] data: ~p~n", [Message]), 
    spawn(?MODULE, run, []). 

回答

6

的問題是,你main/0進程生成run/0,然後立即退出。你應該讓main/0等到run/0完成。這裏是你如何能做到這一點:

-module(inputTest). 
-compile([export_all]). 

run(Parent) -> 
    Message = io:get_line("[New process] Put sth: "), 
    io:format("[New process] data: ~p~n", [Message]), 
    Parent ! {self(), ok}. 

main() -> 
    Message = io:get_line("[Main] Put sth: "), 
    io:format("[Main] data: ~p~n", [Message]), 
    Pid = spawn(?MODULE, run, [self()]), 
    receive 
     {Pid, _} -> 
      ok 
    end. 

產卵run/1 —後,請注意,我們改變了它給我們的進程ID傳遞給它—我們等待從中接收消息。在run/1一旦我們打印輸出,我們發送給父母一條消息,讓它知道我們已經完成。在erl外殼中運行此項產生以下內容:

1> inputTest:main(). 
[Main] Put sth: main 
[Main] data: "main\n" 
[New process] Put sth: run/1 
[New process] data: "run/1\n" 
ok 
+0

非常感謝! 我不知道主進程必須活着才能使用輸入函數。 –