get_feedback() 在主/原始进程中执行。仅仅因为对get_feedback() 的调用发生在对spawn() 的调用之后并不意味着get_feedback() 在生成的进程中执行。在生成的进程中唯一执行的是函数calling:intercept()。
因此,您最终会向生成的进程发送消息,然后在调用get_feedback() 时在主进程中输入receive——这意味着主进程等待来自生成的进程的消息,但生成的进程不发送任何消息(或者至少您没有显示生成的进程向主进程发送消息的任何代码)。
如果您在函数calling:intercept() 中调用get_feedback(),那么get_feedback() 将在派生进程中执行——接收将尝试将主进程发送的消息与派生进程匹配。
另外,如果由于某种原因接收与消息不匹配,而您认为它应该匹配,则像这样重写接收:
receive
Msg -> io:format("~w~n", [Msg])
end
接收将匹配任何消息,然后您可以检查输出以确定实际接收不匹配的原因。
或者,您可以让intercept() 向主进程发送一条消息,然后get_feedback() 可以在主进程中接收消息:
-module(my).
-compile(export_all).
read() ->
{ok, Pairs} = file:consult("calls.txt"),
[spawner(Sender, Receivers) || {Sender, Receivers} <- Pairs].
spawner(Sender, Receivers) ->
io:format("~w, ~w~n", [Sender, Receivers]),
Pid = spawn(my, intercept, []),
io:format("The main process is: ~w.~n", [self()]),
io:format(
"The newly spawned process where intercept() is executing is: ~w~n",
[Pid]
),
Pid ! {self(), {Sender, Receivers} },
get_feedback().
intercept() ->
receive
{From, Pair} ->
io:format("intercept() received message: ~w, from: ~w~n", [Pair, From]),
From ! {self(), "hello"}
end.
get_feedback() ->
receive
{From, Msg} ->
io:format("Main process received message: ~p, from: ~w~n", [Msg, From])
end.
在外壳中:
18> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}
19> my:read().
john, [jill,joe,bob]
The main process is: <0.64.0>.
The newly spawned process where intercept() is executing is: <0.168.0>
intercept() received message: {john,[jill,joe,bob]}, from: <0.64.0>
Main process received message: "hello", from: <0.168.0>
jill, [bob,joe,bob]
The main process is: <0.64.0>.
The newly spawned process where intercept() is executing is: <0.169.0>
intercept() received message: {jill,[bob,joe,bob]}, from: <0.64.0>
Main process received message: "hello", from: <0.169.0>
sue, [jill,jill,jill,bob,jill]
The main process is: <0.64.0>.
The newly spawned process where intercept() is executing is: <0.170.0>
intercept() received message: {sue,[jill,jill,jill,bob,jill]}, from: <0.64.0>
Main process received message: "hello", from: <0.170.0>
bob, [john]
The main process is: <0.64.0>.
The newly spawned process where intercept() is executing is: <0.171.0>
intercept() received message: {bob,[john]}, from: <0.64.0>
Main process received message: "hello", from: <0.171.0>
joe, [sue]
The main process is: <0.64.0>.
The newly spawned process where intercept() is executing is: <0.172.0>
intercept() received message: {joe,[sue]}, from: <0.64.0>
Main process received message: "hello", from: <0.172.0>
[ok,ok,ok,ok,ok]