Bind callback functions to OS signals in C and C++.
Usage
SigFn usage is similar to the os/signal
package from Golang.
C
Basic SigFn usage in C:
#include <stdio.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <time.h>
#endif
static void handle_signal(int signum, void *userdata);
static void sleep_for(int ms);
int main()
{
int flag;
flag = -1;
puts("Paused. Press Ctrl+C to exit.");
while (flag < 0)
{
sleep_for(100);
}
printf("\nReceived signal: %d\n", flag);
return 0;
}
void handle_signal(int signum, void *userdata)
{
*(int*)userdata = signum;
}
void sleep_for(int ms)
{
#ifdef _WIN32
Sleep(ms);
#else
const struct timespec duration = {
.tv_sec = ms / 1000,
.tv_nsec = (ms % 1000) * 1000000,
};
nanosleep(&duration, NULL);
#endif
}
DLL_EXPORT int sigfn_handle(int signum, sigfn_handler_func handler, void *userdata)
attach handler to specific signal
C++
Basic SigFn usage in C++:
#include <iostream>
#include <thread>
int main(int argc, const char **argv)
{
bool loop;
std::cout << std::endl << "Received signal: " << signum << std::endl;
loop = false;
});
std::cout << "Paused. Press Ctrl+C to exit." << std::endl;
loop = true;
while(loop)
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
return 0;
}
DLL_EXPORT void handle(int signum, const handler_function &handler_function)
attach handler to specific signal using copy semantics