can I trap exit(self(), kill)?

匆匆过客 提交于 2019-12-11 02:39:08

问题


when i read an artical from learnyousomeerlang.com,I got a question. http://learnyousomeerlang.com/errors-and-processes

It says that:

Exception source: exit(self(), kill)

Untrapped Result: ** exception exit: killed

Trapped Result: ** exception exit: killed

Oops, look at that. It seems like this one is actually impossible to trap. Let's check something.

but it does not comply with what I test with the code blow:

  -module(trapexit).
  -compile(export_all).
  self_kill_exit()->
  process_flag(trap_exit,true),
  Pid=spawn_link(fun()->timer:sleep(3000),exit(self(),kill)  end),
  receive
    {_A,Pid,_B}->io:format("subinmain:~p output:~p~n",[Pid,{_A,Pid,_B}])
  end.

oupput is: **4> trapexit:self_kill_exit().

subinmain:<0.36.0> output:{'EXIT',<0.36.0>,killed}**

and does not comply with Trapped Result: ** exception exit: killed said before . which is right???


回答1:


The call to self in the body of the function passed as an argument to spawn_link doesn't return the process calling spawn_link. It's being evaluated in the newly spawned process and as a result it will return its pid. Make a following change.

-module(trapexit).
-compile(export_all).
self_kill_exit()->
  process_flag(trap_exit,true),
  Self=self(),
  Pid=spawn_link(fun()->timer:sleep(3000),exit(Self,kill)  end),
  receive
    {_A,Pid,_B}->io:format("subinmain:~p output:~p~n",[Pid,{_A,Pid,_B}])
  end.

Now it should work as expected.

10> c(trapexit).            
{ok,trapexit}
11> trapexit:self_kill_exit().
** exception exit: killed

The book is right. Trapping exit(self(), kill) is not possible.



来源:https://stackoverflow.com/questions/13134078/can-i-trap-exitself-kill

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!