How catch ctrl-c in lua when ctrl-c is sent via the command line

冷暖自知 提交于 2019-12-04 22:49:38

Implementing a SIGINT handler is straightforward using the excellent luaposix library:

local signal = require("posix.signal")

signal.signal(signal.SIGINT, function(signum)
  io.write("\n")
  -- put code to save some stuff here
  os.exit(128 + signum)
end)

Refer to the posix.signal module's API documentation for more information.

windows : SetConsoleCtrlHandler

linux : signal

There are two behaviors of the signal which are undesirable, which will cause complexities in the code.

  1. Program termination
  2. Broken IO

The first behavior can be caught and remembered in a C program by using SetConsoleCtrlHandler/signal. This will allow your function to be called, and you can remember that the system needs to shutdown. Then at some point in the lua code you see it has happened (call to check), and perform your tidy up and shutdown.

The second behavior, is that a blocking operation (read/write) will be cancelled by the signal, and the operation will be unfinished. That would need to be checked at each IO event, and then re-started, or cancelled as appropriate.

There exists io libraries that support this. I know zmq and libuv

Libuv example with lluv binding - https://github.com/moteus/lua-lluv/blob/master/examples/sig.lua

ZeroMQ return EINTR from poll function when user press Ctrl-C

But I do not handle thi byself

Jin Zhou
require('sys')
sys.catch_ctrl_c()

I use this to catch the exit from cli.

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