I'm running a Lua code. (attached below). The code runs fine but when I try to send a SIGINT using CTRL + C
it does not respect it.
local ltn12 = assert(require('ltn12'))
local cjson = assert(require('cjson'))
local http = assert(require('socket.http'))
-- local dbg = assert(require('debugger'))
-- 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)
http.TIMEOUT = 120
local function execute()
print('-- COMMANDER: Starting... ----------')
os.execute('sleep 1')
local ivy_url = 'http://localhost:3000/'
if(ivy_url == nil) then
print('-- COMMANDER: Error :: ivy_url not set ----------')
execute()
end
local _heartbeat = 0
local last_timestamp = nil
local url = nil
while true do
-- _heartbeat used to inform that loop is executing properly.
if _heartbeat % 3 == 0 then
_heartbeat = 0
print('-- COMMANDER: Heartbeat... ----------')
end
_heartbeat = _heartbeat + 1
local response = {}
local since = last_timestamp
last_timestamp = os.date("%Y-%m-%dT%H:%M:%S")
if (since == nil) then
url = ivy_url .. "/switch/sites"
else
url = ivy_url .. "/switch/sites?since=" .. since
end
local one, code, headers, status = http.request {
method = "GET",
url = url,
headers = { Authorization = "Basic " .. tostring("token")},
sink = ltn12.sink.table(response)
}
if(code == 200) then
response_data = cjson.decode(response[1])
for i, site_desc in pairs(response_data['data']) do
print(site_desc)
end
print('-- COMMANDER: Sent API request to Ivy to get site info updated_at ' .. tostring(since) .. ' ----------')
elseif(code == 400) then
last_timestamp = since
response_data = cjson.decode(response[1])
print('-- COMMANDER: Got error in ivy API response : ' .. tostring(response_data['error']) .. ' at ' .. os.date("%Y-%m-%dT%H:%M:%S") .. ' ----------')
else
last_timestamp = since
print('-- COMMANDER: Got error in ivy API response : ' .. tostring(code) .. ' at ' .. os.date("%Y-%m-%dT%H:%M:%S") .. ' ----------')
end
os.execute('sleep 10')
end
end
execute()
How do I achieve this, and ensure that CTRL+C is respected by the Lua program.
I tried using posix.signal
but for no use.
signal.signal(signal.SIGINT, function(signum)
io.write("Interrupting => \n")
-- put code to save some stuff here
os.exit(0)
end)
posix.signal
implements signal handling by setting a Lua hook when a signal is received. The Lua hook will run the next time a Lua instruction is executed. Your program uses LuaSocket, a Lua library written in C. Thus, if a signal comes in while LuaSocket's C code is running, your signal handling code won't run until after it returns. To make this work the way you want, LuaSocket would have to be modified to perform a dummylua_call
whenever it gets interrupted by a signal. This would then trigger your Lua hook to run. I opened https://github.com/diegonehab/luasocket/issues/319 about this.