Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I catch SIGINT without closing xterm?

Tags:

Here is my script;

#!/bin/bash
trap '' SIGINT
xterm  &
wait

I run it and an xterm pops up. Then I focus my keyboard on the originating terminal window and hit ^C. I would like nothing to happen, but instead the child xterm goes away.

(Ideally, I want to install my own trap handler, but this is a baby step)

Using disown after forking xterm detaches the xterm from the parent and then ^C doesn't do anything to the xterm, but then wait doesn't work.

I just want to block SIGINT from getting to xterm.

like image 523
Mark Lakata Avatar asked Aug 16 '16 00:08

Mark Lakata


2 Answers

Pressing CTRL+C will send SIGINT signal to each process under the same group of the foreground process's. So xterm goes away too. You can use setsid to change the group id of xterm's.

#!/bin/bash
trap 'echo "Caught SIGINT"' SIGINT
setsid xterm &
wait

wait will be interrupted by SIGINT too. So if you want to wait after pressing CTRL+C, you need to wait again according to suggestion of @fbohorquez.

#!/bin/bash
trap 'R=true;echo "Caught SIGINT"' SIGINT
setsid xterm &
while : ; do
    R=false
    wait
    [ $R == false ] && break
done
like image 22
Wenyi Li Avatar answered Sep 26 '22 16:09

Wenyi Li


When you send SIGINT to bash script the signal is propagate to current process in the script, then it executes command in trap. So "wait" is interrupted. You must do that "wait" run again.

Also you must do that all jobs are launched in their own process groups (set -m). From the set man page:

set -m

Monitor mode. Job control is enabled. This option is on by default for interactive shells on systems that support it (see JOB CONTROL above). Background processes run in a separate process group and a line containing their exit status is printed upon their completion.

#!/bin/bash
set -m
trap 'R=true' SIGINT
xterm &
while : ; do
    R=false
    wait
   [[ $R == true ]] || break
done

You can see commands that it run with '-x' option in shebang.

like image 72
fbohorquez Avatar answered Sep 22 '22 16:09

fbohorquez