Input 如何从“控制台”中读取;“不主要”;过程
如何在新流程中读取标准数据?我只能在主流程中放置行并打印它。我应该通过获得在线控制台设备或类似设备,还是不可能 我的代码:Input 如何从“控制台”中读取;“不主要”;过程,input,concurrency,erlang,Input,Concurrency,Erlang,如何在新流程中读取标准数据?我只能在主流程中放置行并打印它。我应该通过获得在线控制台设备或类似设备,还是不可能 我的代码: -module(inputTest). -compile([export_all]). run() -> Message = io:get_line("[New process] Put sth: "), io:format("[New process] data: ~p~n", [Message]). main() -> Message =
-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, []).
问题是您的
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
shell中运行此命令会产生以下结果:
1> inputTest:main().
[Main] Put sth: main
[Main] data: "main\n"
[New process] Put sth: run/1
[New process] data: "run/1\n"
ok
非常感谢你!我不知道主进程必须处于活动状态才能使用输入函数。