2

I want to launch a background process from bash in such a way that I can then send SIGINT signals to it (eg: via kill or htop). How do I do that?

By default, when a process is launched in the backround, SIGINT and SIGQUIT are ignored (see this question).

drevicko
  • 14,382
  • 15
  • 75
  • 97

1 Answers1

2

If the process is execed (=isn't just a subshell but is based on binary), you can run it through a wrapper that'll undo the SIGINT/SIGQUIT ignore:

reset_sigint.c:

#include <signal.h>
#include <unistd.h>
int main(int C, char**V)
{
    sigaction(SIGINT,&(struct sigaction){.sa_handler=SIG_DFL}, 0);
    execvp(V[1],V+1);
    return 127;
}

To prevent the SIGINT/SIGQUIT ignore more generically for any process run as a command in the shell, you can run it with set -m on

sh -c 'set -m; ( sleep 10 )& ps -p $! -o ignored'
#compare with: sh -c '( sleep 10 )& ps -p $! -o ignored'

but that'll run the command in a separate process group as a (possibly undesirable) sideffect.

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • Oddly, I didn't manage to get the second option working for me. Not sure why - I'm running a bash script in the background from another bash script. The bg script is launching a python program. I tried `set -m` in the second bash script, but python still didn't get SIGINTs. In the end, just adding a SIGINT handler in Python that raises `KeyboardInterrupt` did the trick, as suggested [here](https://stackoverflow.com/questions/45106725/why-do-shells-ignore-sigint-and-sigquit-in-backgrounded-processes/45106961#comment85361685_45106961). – drevicko Mar 09 '18 at 09:28
  • Try `bash -c ' python -c "import time; time.sleep(100)" & ps -o ignored $!'` vs `bash -c ' set -m ; python -c "import time; time.sleep(100)" & ps -o ignored $!'`. It works for me. The second mask doesn't end with 6 (==1<<1|1<<2) anymore which means SIGINT and SIGCONT aren't blocked in the second python process. Anyway, your approach should work too. It's only shells that refuse to establish a handler for an ignored signal. The system (and consequently other langs) doesn't have a problem with it. – Petr Skocik Mar 10 '18 at 19:54
  • ok, now I'm officially confused! A simple set of scripts emulating my real ones with a `set -m` in the first (that calls a second bash script in bg that calls python) and python gets SIGINTs! Perhaps I only tried `set -m` in the second script?? When I've a little time, I might have another look at my production scripts, see if there's something else might be confusing things? For now, I've accepted your answer (: Thx! – drevicko Mar 12 '18 at 09:46