ruby at_exit exit status

2019-03-25 08:00发布

Can i determine selves process exit status in at_exit block?

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

2条回答
霸刀☆藐视天下
2楼-- · 2019-03-25 08:31

using idea from 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
查看更多
Summer. ? 凉城
3楼-- · 2019-03-25 08:38

Although the documentation on this is really thin, $! is set to be the last exception that occurs, and after an exit() call this is a SystemExit exception. Putting those two together you get this:

at_exit do
  if ($!.success?)
    print 'Success'
  else
    print 'Failure'
  end
end
查看更多
登录 后发表回答