2012-10-30 58 views
2

当我从learnyousomeerlang.com读到一篇文章时,我有一个问题。 http://learnyousomeerlang.com/errors-and-processes我可以陷阱退出(self(),kill)吗?

它说:

异常源:exit(self(), kill)

未捕获的结果:** exception exit: killed

被困结果:** exception exit: killed

哎呀,看看那个。看起来这个实际上是不可能陷入的。让我们来检查一下。

,但它不符合我的代码的打击测试:

-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是: ** 4> trapexit:self_kill_exit()。

subinmain:< 0.36.0>输出:{ '退出',< 0.36.0>,杀死} **

,不与囚禁结果符合:**退出异常:杀害之前说。哪个是对的???

回答

4

在作为参数传递给spawn_link的函数体中调用self不会返回调用spawn_link的进程。它正在新生成的进程中进行评估,因此它将返回其PID。进行以下更改。

-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. 

现在它应该按预期工作。

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

这本书是正确的。诱捕exit(self(), kill)是不可能的。