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

2019-07-19 07:45发布

问题:

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.



标签: erlang