Woj*_*moń 2 concurrency erlang input
如何在新进程中读取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, []).
Run Code Online (Sandbox Code Playgroud)
问题是您的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 Code Online (Sandbox Code Playgroud)
产生后run/1- 并注意我们更改它以将我们的进程ID传递给它 - 我们等待从它接收消息.在run/1我们一旦打印到输出,我们送父的消息,让它知道我们就大功告成了.在erlshell中运行它会产生以下结果:
1> inputTest:main().
[Main] Put sth: main
[Main] data: "main\n"
[New process] Put sth: run/1
[New process] data: "run/1\n"
ok
Run Code Online (Sandbox Code Playgroud)