如何在Haskell中编写Ctrl-C处理程序? [英] How to write Ctrl-C handler in Haskell?

查看:51
本文介绍了如何在Haskell中编写Ctrl-C处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下方法:

import System.Exit
import System.Posix.Signals
import Control.Concurrent (threadDelay)

main :: IO ()
main = do
  installHandler keyboardSignal (Catch (do exitSuccess)) Nothing
  threadDelay (1000000000)

但是它仅输出:

^CTest.hs: ExitSuccess

上的

,而不是退出.我应该如何正确做?

on Ctrl-C, instead of exiting. How should I do it properly?

推荐答案

来自installHandler的文档:

已安装一个处理程序,该处理程序将在收到信号时(或之后不久)在新线程中调用动作.

a handler is installed which will invoke action in a new thread when (or shortly after) the signal is received.

exitWith:

注意:在GHC中,应从主程序线程中调用exitWith,以退出该进程.当从另一个线程调用时,exitWith会照常抛出ExitException,但是该异常不会导致进程本身退出.

Note: in GHC, exitWith should be called from the main program thread in order to exit the process. When called from another thread, exitWith will throw an ExitException as normal, but the exception will not cause the process itself to exit.

因此,exitSuccess处理程序不会结束该过程,这是预期的(尽管是意外的;)行为.

So an exitSuccess handler doesn't end the process, and that's expected (although unexpected ;) behaviour.

如果您要立即采取行动,

If you want immediate action,

import System.Exit
import System.Posix.Signals
import Control.Concurrent

main :: IO ()
main = do
  tid <- myThreadId
  installHandler keyboardSignal (Catch (killThread tid)) Nothing
  threadDelay (1000000000)

在收到信号后立即杀死线程.

kills the thread immediately upon receiving the signal.

如果您想成功退出,请不要大张旗鼓

Less drastic, if you want a successful exit, would be

import System.Exit
import System.Posix.Signals
import Control.Concurrent
import qualified Control.Exception as E

main :: IO ()
main = do
  tid <- myThreadId
  installHandler keyboardSignal (Catch (E.throwTo tid ExitSuccess)) Nothing
  threadDelay (10000000)

我认为它也可以可靠地工作,但是我不确定.

I think it will also work reliably, but I'm not entirely sure.

这篇关于如何在Haskell中编写Ctrl-C处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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