0

Process A sets a trap. It then creates a child process B. How can I clear the trap set by process A?

processA

#! /bin/bash
# processA.sh
trap '' 15
sh processB.sh

processB

#! /bin/bash
# processB.sh    
echo "Current trap"
trap -p    
echo "Clearing trap 15"
trap - 15    
echo "New trap"
trap -p

Output

Current trap
trap -- '' TERM
Clearing trap 15
New trap
trap -- '' TERM

In above example, I am clearing a trap in the child process B but it is not getting cleared. Operating system is Linux.

bluetech
  • 1,380
  • 3
  • 13
  • 22

1 Answers1

0

In general, you cancel a trap for signal 15 with trap 15. That would include resetting an ignored signal back to the default when the current shell started ignoring it.

However, some experimentation (with Bash 3.2.57 on macOS Sierra 10.12) shows that if the signal was ignored when the process was started (inherited from the parent) then you can't reset to the default handling — it continues to be ignored. Further, attempts like trap ': do nothing' 15 followed by trap 15 do not do the job.

I wrote a C program called iqon (interrupt, quit on — first version in 1989) to ensure that signals were trapped (or ignored) by the command that it then executed.

iqon -s 15 -- bash processB.sh

Variations on this theme work.

Note that a simple-minded version of iqon which only sets signal SIGTERM to the default status (no argument handling) could be as simple as:

#include <signal.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    if (argc <= 1)
    {
        fprintf(stderr, "Usage: %s cmd [arg ...]", argv[0]);
        return 1;
    }
    signal(SIGTERM, SIG_DFL);
    execvp(argv[1], &argv[1]);
    perror(argv[1]);
    return 1;
}

Clearly, you can make it more complex without any difficulty. My version supports a help message like this:

Usage: iqon [-dhV] [-s signal] [-i signal] cmd [args ...]
  -d         Set interrupt and quit to default
  -h         Print this help and exit
  -i signal  Ignore signal (number)
  -s signal  Set default for signal (number)
  -V         Print version information and exit

The default (setting interrupt and quit to the default behaviour) is a legacy from its original purpose — for running programs from within programs created by a 4GL where the interrupt and quit signals were ignored. It's also where the name came from: interrupt and quit on.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Ok. Yes, I do not have control over the parent process in the problem that I am working on. I have to kill the process with -9 as 15 won't work as there is no other option. +1 for iqon – bluetech Oct 07 '16 at 00:18