我可以捕获exit(self(),kill)吗? [英] can I trap exit(self(), kill)?

查看:114
本文介绍了我可以捕获exit(self(),kill)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从learnyousomeerlang.com看到一个artical时,我有一个问题。
http://learnyousomeerlang.com/errors-and-processes

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

它说:


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

Untrapped结果 *异常退出:死亡

被困的结果 **异常退出: / code>

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

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

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

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

推荐答案

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

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

这本书是对的。陷阱 exit(self(),kill)是不可能的。

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

这篇关于我可以捕获exit(self(),kill)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆