How to intercept Linux signals? (in C)

I need to intercept and track signals from any binaries, for example strace, under Linux. I do not need such detailed output as the real one strace. I just want to know how it works, how I can intercept a signal and how to trace it. Thanks in advance:)

+3
source share
3 answers

strace uses a system call ptrace()for tracking, which also allows you to intercept (and possibly manipulate) signals sent to the process.

Here is a tiny example:

#include <sys/ptrace.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    /* simple example, child is traced, uses alarm which causes a signal to be
     * set up */
    pid_t child;

    child = fork();
    if (child == 0)
    {
        ptrace(PTRACE_TRACEME, 0, NULL, NULL);
        alarm(3);
        while(1)
        {
        }
        exit(0);
    }

    /* parent */
    while(1)
    {
        int wstatus;
        int signum;

        wait(&wstatus);
        if (WIFEXITED(wstatus) || WIFSIGNALED(wstatus))
            break;

        signum = WSTOPSIG(wstatus);
        printf("child stopped with signal %d\n", signum);
        /* resume execution */
        ptrace(PTRACE_CONT, child, NULL, signum);
    }

    return 0;
}
+3
source

This is the simplest implementation!

- int main() signal(), , . - ; - ( ):

    signal(SIGFPE, SignalHandler);
    signal(SIGILL, SignalHandler);
    signal(SIGINT, SignalHandler);
    signal(SIGSEGV, SignalHandler);
    signal(SIGTERM, SignalHandler);
#ifndef WIN32
    signal(SIGHUP, SignalHandler);
    signal(SIGQUIT, SignalHandler);
    signal(SIGKILL, SignalHandler);
    signal(SIGPIPE, SignalHandler);
    signal(SIGCHLD, SignalHandler);
#endif

. void int: void SignalHandler(int signal_number):

void SignalHandler(int signal_number)
{
    printf("Received signal: %s\n", strsignal(signal_number);
    // Do something
}

! , raise(SIGNAL_NAME); , raise(SIGTERM);!

+1

- , - , . . .

Needless to say, if you are writing a debugger, understand ptrace ().

0
source

Source: https://habr.com/ru/post/1726165/


All Articles