如何确定按下Ctrl + C后所有线程都已被杀死 [英] How to be certain that all threads have been killed upon pressing Ctrl+C

查看:158
本文介绍了如何确定按下Ctrl + C后所有线程都已被杀死的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 gchi 中运行servant服务器和另一个后台线程(通过 async )。当我在GHCi提示符下按下 Ctrl + c 时,servant服务器正常关闭,但后台线程继续运行。只有退出整个GHCi会议似乎真的终止它。



两个问题:


  • 这种行为只是因为我在GHCi ?如果我编译了一个二进制文件,运行它,然后按下Ctrl + C,后台线程是否仍然运行?

  • 如何正确解决此问题?


  • 解决方案


    这种行为只是因为我在GHCi吗?如果我编译了一个二进制文件,运行它,然后按Ctrl + C就可以了,后台线程仍能继续运行吗?


    在一个已编译的二进制文件中,如果^ C导致主要线程结束,那么进程将结束,所有线程也会(突然)结束作为副作用。 ^ C不会导致 main 线程结束;


    如何正确解决这个问题?


    也许你可以看到 UserInterrupt 例外时会注意到^ C已被命中并关闭了您在异常处理程序中产生的任何线程。



    我说可能,因为^ C处理有点复杂,servant安装了自定义处理程序是可行的。在这种情况下,您可能需要查看信号通过 unix 包处理。 (不知道Windows系统是什么。)

    I'm running a servant server and another background thread (via async) in gchi. When I press Ctrl+c on the GHCi prompt, the servant server shuts down properly, but my background thread keeps running. Only quitting the entire GHCi session seems to really terminate it.

    Two questions:

    • Is this behaviour only because I'm in GHCi? If I compiled a binary, ran it, and then pressed Ctrl+C on it, would the background-thread still keep running?
    • How do I solve for this properly?

    解决方案

    Is this behaviour only because I'm in GHCi? If I compiled a binary, ran it, and then pressed Ctrl+C on it, would the background-thread still keep running?

    In a compiled binary, if ^C causes the main thread to end, then the process will end and all threads will also be (abruptly) ended as a side effect. It is not a given that ^C causes the main thread to end; see the discussion of signal handling below.

    How do I solve for this properly?

    Probably you can catch the UserInterrupt exception to notice when ^C has been hit and shut down any threads you spawned in the exception handler.

    I say "probably" because ^C handling is a bit complicated, and it's feasible that servant has installed custom handlers. In that case you may need to look into signal handling via the unix package. (Dunno what the equivalent is for Windows systems.)

    这篇关于如何确定按下Ctrl + C后所有线程都已被杀死的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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