gpt4 book ai didi

haskell - 如何在 Haskell 中编写 Ctrl-C 处理程序?

转载 作者:行者123 更新时间:2023-12-03 13:31:30 25 4
gpt4 key购买 nike

我尝试了以下方法:

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

Ctrl-C ,而不是退出。我应该如何正确地做到这一点?

最佳答案

来自 installHandler 的文档:

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



exitWith:

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处理程序不会结束该过程,这是预期的(尽管是意外的;)行为。

如果您想立即采取行动,
import System.Exit
import System.Posix.Signals
import Control.Concurrent

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

收到信号后立即杀死线程。

不那么激烈,如果你想成功退出,那就是
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)

我认为它也可以可靠地工作,但我不完全确定。

关于haskell - 如何在 Haskell 中编写 Ctrl-C 处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13441676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com