2 つのリンクされたプロセスchild
とが与えられた場合、プロセスは正常に終了 (終了)したことをparent
どのようにchild
検出しますか?parent
Erlang の完全な初心者である私は、他に何もすることがないプロセスは、 を使用して終了すると考えていましたexit(normal)
。これにより、リンクされたすべてのプロセスが通知されます。
trap_exit
に設定されているプロセスの動作はfalse
、シグナルを無視することです。trap_exit
に設定されているプロセスの動作は、終了プロセスのプロセス ID であるメッセージtrue
を生成することです。{'EXIT', pid, normal}
pid
私がこれを考える理由は、Learn You Some Erlang for Great Goodと、Erlang のドキュメントに次のように記載されているためです。
終了理由がアトムの正常な場合、プロセスは正常に終了したと言われます。実行するコードがなくなったプロセスは、正常に終了します。
コマンドプロンプトにexit(normal
) が表示され、以下のコードが機能するため、明らかに間違っています (?) 。** exception exit: normal
実行するコードがなくなったために終了しても、例外は生成されず、コードが機能しません。
例として、次のコードを考えてみましょう。
-module(test).
-export([start/0,test/0]).
start() ->
io:format("Parent (~p): started!\n",[self()]),
P = spawn_link(?MODULE,test,[]),
io:format(
"Parent (~p): child ~p spawned. Waiting for 5 seconds\n",[self(),P]),
timer:sleep(5000),
io:format("Parent (~p): dies out of boredom\n",[self()]),
ok.
test() ->
io:format("Child (~p): I'm... alive!\n",[self()]),
process_flag(trap_exit, true),
loop().
loop() ->
receive
Q = {'EXIT',_,_} ->
io:format("Child process died together with parent (~p)\n",[Q]);
Q ->
io:format("Something else happened... (~p)\n",[Q])
after
2000 -> io:format("Child (~p): still alive...\n", [self()]), loop()
end.
これにより、次のような出力が生成されます。
(erlide@127.0.0.1)> test:start().
Parent (<0.145.0>): started!
Parent (<0.145.0>): child <0.176.0> spawned. Waiting for 5 seconds
Child (<0.176.0>): I'm... alive!
Child (<0.176.0>): still alive...
Child (<0.176.0>): still alive...
Parent (<0.145.0>): dies out of boredom
ok
(erlide@127.0.0.1)10> Child (<0.176.0>): still alive...
Child (<0.176.0>): still alive...
Child (<0.176.0>): still alive...
Child (<0.176.0>): still alive...
Child (<0.176.0>): still alive...
Child (<0.176.0>): still alive...
Child (<0.176.0>): still alive...
exit(pid(0,176,0),something).
Child process died together with parent ({'EXIT',<0.194.0>,something})
exit(pid(0,176,0),something)
子が永久に存続しないようにするために、コマンドを手動で実行する必要があった場合。に変更ok.
するstart
とexit(normal)
、実行は次のようになります
(erlide@127.0.0.1)3> test:start().
Parent (<0.88.0>): started!
Parent (<0.88.0>): child <0.114.0> spawned. Waiting for 5 seconds
Child (<0.114.0>): I'm... alive!
Child (<0.114.0>): still alive...
Child (<0.114.0>): still alive...
Parent (<0.88.0>): dies out of boredom
Child process died together with parent ({'EXIT',<0.88.0>,normal})
** exception exit: normal
私の具体的な質問は次のとおりです。
- 上記のコードを期待どおりに動作させるにはどうすればよいですか。つまり、親プロセスを変更せずに、子プロセスが親プロセスと一緒に停止するようにするにはどうすればよいですか?
- が CLI で を
exit(normal)
生成するのはなぜですか?** exception exit: normal
例外を正常なものと考えるのは難しいです。Erlang ドキュメントの香りは何を意味していますか?
これらは非常に基本的な質問に違いないと思いますが、これを理解できないようです.... Windows(x64)でErlang 5.9.3.1を使用しています。