How to be certain that all threads have been killed upon pressing Ctrl+C

淺唱寂寞╮ 提交于 2020-01-05 07:10:30

问题


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?

回答1:


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.)



来源:https://stackoverflow.com/questions/46722102/how-to-be-certain-that-all-threads-have-been-killed-upon-pressing-ctrlc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!