简单代码:运行报表给出不同的输出
-module(on_exit).
-export([on_exit/2, test/0]).
on_exit(Pid, Fun) ->
spawn(fun() ->
Ref = erlang:monitor(process, Pid),
receive
{'DOWN', Ref, process, Pid, Why} ->
Fun(Why)
end
end).
test() ->
Fun1 = fun() -> receive Msg -> list_to_atom(Msg) end end,
Pid1 = spawn(Fun1),
Fun2 = fun(Why) -> io:format("~w died with error: ~w~n", [Pid1, Why]) end,
_Pid2 = spawn(on_exit, on_exit, [Pid1, Fun2]),
Pid1 ! hello.
在shell:
1> c(on_exit).
{ok,on_exit}
2> on_exit:test().
<0.39.0> died with error: noproc
hello
3>
=ERROR REPORT==== 9-Apr-2017::05:16:54 ===
Error in process <0.39.0> with exit value: {badarg,[{erlang,list_to_atom,[hello],[]},{on_exit,'-test/0-fun-0-',0,[{file,"on_exit.erl"},{line,14}]}]}
预期输出:
5> Pid1 ! hello.
<0.35.0> died with error: {badarg,[{erlang,list_to_atom,[hello],[]}]}
hello
6>
=ERROR REPORT==== 9-Apr-2017::05:15:47 ===
Error in process <0.35.0> with exit value: {badarg,[{erlang,list_to_atom,[hello],[]}]}
事实上,预期输出是我看看我是否将test()中的每行都粘贴到了shell中。为什么我在函数内运行相同的行时会出现noproc(无进程)错误?
从docs:
12.8监视器
的替代方法链路监视器。进程Pid1可以通过调用BIF erlang:monitor(process,Pid2)为Pid2创建一个 监视器。 函数返回一个引用Ref。
如果PID2与退出原因原因终止,一个“向下”消息被发送 到PID1:
{'DOWN', Ref, process, Pid2, Reason}
如果PID2不存在时,“向下”消息被立即用 原因集发送到noproc。
如果您在Pid1之前添加'timer:sleep(100)',您会得到预期的输出! hello.'? – Dogbert
@Dogbert,是的!这似乎表明'spawn()'异步执行。 – 7stud