2009-07-17 73 views
11

我可以在at_exit块中确定自己的进程退出状态吗?ruby​​ at_exit退出状态

at_exit do 
    if this_process_status.success? 
    print 'Success' 
    else 
    print 'Failure' 
    end 
end 

回答

14

使用想法从tadman

at_exit do 
    if $!.nil? || $!.is_a?(SystemExit) && $!.success? 
    print 'success' 
    else 
    code = $!.is_a?(SystemExit) ? $!.status : 1 
    print "failure with code #{code}" 
    end 
end 
17

尽管关于此的文档非常薄,但$!被设置为发生的最后一个异常,并且在exit()调用之后,这是一个SystemExit异常。把那两个聚一聚这样的:

at_exit do 
    if ($!.success?) 
    print 'Success' 
    else 
    print 'Failure' 
    end 
end 
+0

这将是唯一的,如果出口将被调用的情况。 当然我可以测试$!是零还是SystemExit成功回答真实? 但是有可能获得Process :: Status对象,或者它不是为顶级进程创建的吗? – tig 2009-07-18 12:12:23

+0

使用你的想法我得到的答案和张贴,但我不知道哪个答案更好地标记 - 你的或我的? – tig 2009-07-20 16:52:01