Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

torch

lua

luajit

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

like image 891
lars Avatar asked Sep 01 '15 17:09

lars


People also ask

How can I catch a Ctrl C event?

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.

How do you catch SIGINT?

When Ctrl+C is pressed, SIGINT signal is generated, we can catch this signal and run our defined signal handler.

What signal Ctrl C sends?

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

Is Ctrl C a SIGINT?

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.


1 Answers

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.

like image 142
Arto Bendiken Avatar answered Oct 24 '22 22:10

Arto Bendiken