magicleon94
magicleon94

Reputation: 5162

Terminate a process started by a bash script with CTRL-C

I am having an issue with terminating the execution of a process inside a bash script.

Basically my script does the following actions:

  1. Issue some starting commands
  2. Start a program who waits for CTRL+C to stop
  3. Do some post-processing on data retreived by the program

My problem is that when I hit CTRL+C the whole script terminates, not just the "inner" program.

I have seen around some scripts that do this, this is why I think it's possible.

Upvotes: 8

Views: 6270

Answers (1)

Siguza
Siguza

Reputation: 23820

You can set up a signal handler using trap:

trap 'myFunction arg1 arg2 ...' SIGINT;

I suggest keeping your script abortable overall, which you can do by using a simple boolean:

#!/bin/bash

# define signal handler and its variable
allowAbort=true;
myInterruptHandler()
{
    if $allowAbort; then
        exit 1;
    fi;
}

# register signal handler
trap myInterruptHandler SIGINT;

# some commands...

# before calling the inner program,
# disable the abortability of the script
allowAbort=false;
# now call your program
./my-inner-program
# and now make the script abortable again
allowAbort=true;

# some more commands...

In order to reduce the likelihood of messing up with allowAbort, or just to keep it a bit cleaner, you can define a wrapper function to do the job for you:

#!/bin/bash

# define signal handler and its variable
allowAbort=true;
myInterruptHandler()
{
    if $allowAbort; then
        exit 1;
    fi;
}

# register signal handler
trap myInterruptHandler SIGINT;

# wrapper
wrapInterruptable()
{
    # disable the abortability of the script
    allowAbort=false;
    # run the passed arguments 1:1
    "$@";
    # save the returned value
    local ret=$?;
    # make the script abortable again
    allowAbort=true;
    # and return
    return "$ret";
}

# call your program
wrapInterruptable ./my-inner-program

Upvotes: 6

Related Questions