I would like to know when the user from a command line presses control-c so I can save some stuff.
How do I do this? I've looked but haven't really seen anything.
Note: I'm somewhat familiar with lua, but I'm no expert. I mostly use lua to use the library Torch (http://torch.ch/)
The CTRL + C is one signal in C or C++. So we can catch by signal catching technique. For this signal, the code is SIGINT (Signal for Interrupt). Here the signal is caught by signal() function.
When Ctrl+C is pressed, SIGINT signal is generated, we can catch this signal and run our defined signal handler.
The SIGINT signal is sent to a process by its controlling terminal when a user wishes to interrupt the process. This is typically initiated by pressing Ctrl + C , but on some systems, the "delete" character or "break" key can be used. The SIGKILL signal is sent to a process to cause it to terminate immediately (kill).
SIGINT is the signal sent when we press Ctrl+C. The default action is to terminate the process. However, some programs override this action and handle it differently. One common example is the bash interpreter.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With