From 900629838c633cf8b576df4c1d231e9c46998a37 Mon Sep 17 00:00:00 2001 From: Vanya Sergeev Date: Tue, 5 Jul 2016 03:13:46 -0700 Subject: [PATCH] blocks/sources/rtlsdr: add sigterm handler to cancel reading and allow device close after rtlsdr_read_async() returns. resolves #8. --- radio/blocks/sources/rtlsdr.lua | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/radio/blocks/sources/rtlsdr.lua b/radio/blocks/sources/rtlsdr.lua index 161e9446a..f3314b1e8 100644 --- a/radio/blocks/sources/rtlsdr.lua +++ b/radio/blocks/sources/rtlsdr.lua @@ -29,6 +29,7 @@ local ffi = require('ffi') local block = require('radio.core.block') local platform = require('radio.core.platform') local types = require('radio.types') +local async = require('radio.core.async') local RtlSdrSource = block.factory("RtlSdrSource") @@ -194,15 +195,38 @@ local function read_async_callback_factory(pipes) return read_async_callback end +function sigterm_handler_factory(dev) + local ffi = require('ffi') + + ffi.cdef[[ + typedef struct rtlsdr_dev rtlsdr_dev_t; + int rtlsdr_cancel_async(rtlsdr_dev_t *dev); + ]] + local librtlsdr = ffi.load('rtlsdr') + + function sigterm_handler(sig) + librtlsdr.rtlsdr_cancel_async(ffi.cast('rtlsdr_dev_t *', dev)) + end + + return ffi.cast('void (*)(int)', sigterm_handler) +end + function RtlSdrSource:run() -- Initialize the rtlsdr in our own running process self:initialize_rtlsdr() + -- Register SIGTERM signal handler + local handler, handler_state = async.callback(sigterm_handler_factory, tonumber(ffi.cast("intptr_t", self.dev[0]))) + ffi.C.signal(ffi.C.SIGTERM, handler) + -- Start asynchronous read local ret = librtlsdr.rtlsdr_read_async(self.dev[0], read_async_callback_factory(self.outputs[1].pipes), nil, 0, 32768) if ret ~= 0 then error("rtlsdr_read_async(): " .. tostring(ret)) end + + -- Close rtlsdr + librtlsdr.rtlsdr_close(self.dev[0]) end return RtlSdrSource