/*
 * fhist - file history and comparison tools
 * Copyright (C) 1991-1995, 1998, 1999, 2002, 2008, 2010 Peter Miller
 *
 * Derived from a work
 * Copyright (C) 1990 David I. Bell.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include <common/ac/signal.h>
#include <common/ac/unistd.h>

#include <fhist/breaks.h>


static int breakflag;           /* TRUE if breaks are disabled */

#ifndef HAVE_SIGHOLD
#ifdef HAVE_SIGPROCMASK
static sigset_t oldsigs;
#endif
#endif


/*
 * Function to disable signals during a critical section of code.
 * The signals are held until the critical section is done.
 */

void
breaksoff(void)
{
    if (breakflag)
        return;
    breakflag = 1;
#ifdef HAVE_SIGHOLD
    sighold(SIGHUP);
    sighold(SIGINT);
    sighold(SIGQUIT);
    sighold(SIGTERM);
#else
#ifdef HAVE_SIGPROCMASK
    {
        sigset_t        set;

        sigemptyset(&set);
        sigaddset(&set, SIGHUP);
        sigaddset(&set, SIGINT);
        sigaddset(&set, SIGQUIT);
        sigaddset(&set, SIGTERM);
        sigprocmask(SIG_BLOCK, &set, &oldsigs);
    }
#endif /* HAVE_SIGPROCMASK */
#endif /* !HAVE_SIGHOLD */
}


/*
 * Function to reenable signals when critical code is complete.
 */

void
breakson(void)
{
    if (!breakflag)
        return;
#ifdef HAVE_SIGHOLD
    sigrelse(SIGHUP);
    sigrelse(SIGINT);
    sigrelse(SIGQUIT);
    sigrelse(SIGTERM);
#else
#ifdef HAVE_SIGPROCMASK
    sigprocmask(SIG_SETMASK, &oldsigs, (sigset_t *)0);
#endif /* HAVE_SIGPROCMASK */
#endif /* !HAVE_SIGHOLD */
    breakflag = 0;
}
