0

I'm trying to disable core dumps being generated for individual signals in my application.

ulimit -c 0 wont work in my case, since it needs to be executed before application start and will completely disable core dumps for all signals.

Is it possible to make such an exception for a single signal or at least disable core dump generation for a certain amount of time (eg. during sending the SIGHUP signal)?

RA.
  • 969
  • 13
  • 36

2 Answers2

1
#include <setjmp.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <unistd.h>

static sigjmp_buf sigjmp;
static void sighup_handler(int signo) {
    siglongjmp(&sigjmp, signo);
}

int main(int argc, char **argv) {
    struct sigaction sighup_action = {
        .sa_handler = &sighup_handler,
        .sa_flags = SA_RESETHAND,
    };
    sigset_t sigset;
    int signo;

    sigemptyset(&sighup_action.sa_mask);
    sigaddset(&sighup_action.sa_mask, SIGHUP);
    sigprocmask(SIG_BLOCK, &sighup_action.sa_mask, &sigset);
    sigaction(SIGHUP, &sighup_action, NULL);
    signo = sigsetjmp(&sigjmp, 1);
    if (signo) {
        struct rlimit rl = { .rlim_cur = 0, .rlim_max = 0 };
        setrlimit(RLIMIT_CORE, &rl);
        sigprocmask(SIG_SETMASK, &sigset, NULL);
        kill(getpid(), signo);
        abort();  /* just in case */
        _exit(128 | signo);
    }
    sigprocmask(SIG_SETMASK, &sigset, NULL);

    pause(); /* or whatever the rest of your program does */
}

You can install a signal handler which sets RLIMIT_CORE to 0, then proceeds with the default signal action. If you use SA_RESETHAND, the default signal handler is automatically reinstalled right before the signal handler is run. However, setrlimit is not async-signal-safe, so we should not call it from inside a signal handler, hence using siglongjmp to return to normal code and performing it there.

ephemient
  • 198,619
  • 38
  • 280
  • 391
  • Thank you so much. – RA. May 23 '17 at 05:05
  • siglongjmp does not remove the async-signal-safe requirement of the following code. Using siglongjmp is almost always a sign that you are just completely ignoring the safeness requirements. So it's more readable to just call setrlimit in the handler. See https://man7.org/linux/man-pages/man3/siglongjmp.3.html . """recommends avoiding the use of these functions from signal handlers and goes on to point out that if these functions are called from a signal handler [...], the behavior is undefined if the program subsequently makes a call to a non-async-signal-safe function.""" – textshell Apr 30 '22 at 09:48
0

Just add an empty signal handler for SIGHUP, or ignore it like this:

signal(SIGHUP, SIG_IGN);
  • This doesn't abort when the signal is received, which is apparently something the original questioner is interested in. – ephemient May 24 '17 at 03:14