0

I created this script:

code fn()
{
  sleep 1001
}

fn &
sleep 1000
echo "finish"

When I runt it and list processes (it's pid is 11570):

$ ps xao pid,ppid,pgid,command | grep 11570 |grep -v grep

11570 24322 11570 /bin/bash ./bash.sh
11577 11570 11570 /bin/bash ./bash.sh
11578 11570 11570 sleep 1000
11579 11577 11570 sleep 1001

then I'm killing it with ctrl+c and same ps returns:

11577     1 11570 /bin/bash ./bash.sh
11579 11577 11570 sleep 1001

Then:

kill -INT 11579 

And nothing happnes (still same processes in bg)

I know that ctrl+c is same as killing it by:

kill -INT -11570 

The same happens (same two processes are still in background). Then - in next run - I killed processes within group one by one and found that the only one which cares is sleep which is not in function.

I thought then that main process finishes then and that's why it finishes. But then 'finish' should be printed. (as it is when I interrupt just this sleep)

And now the questions are:

Why is only one sleep answering to interruption signal?

How to make this script cleanup processes in backgound on interruption?

Yuankun
  • 6,875
  • 3
  • 32
  • 34
ravenwing
  • 668
  • 3
  • 20
  • Sending the process to background detaches it from the current shell and runs on its own shell. This [answer](https://stackoverflow.com/a/1911387/2834978) shows how to kill it. – LMC Apr 13 '18 at 15:21
  • @LuisMuñoz, as for killing this process I know how to kill it. (already answered). But how does this detachement explains not reacting for INT signal for one sleep, and reacting for other? – ravenwing Apr 13 '18 at 15:31
  • The INT signal is sent to current PID, not the background PID. – LMC Apr 13 '18 at 15:35
  • @LuisMuñoz I have killed them one by one. Let me stick with pid from example: i did `kill -INT 11579` before `ctrl+c` – ravenwing Apr 13 '18 at 15:42
  • 2
    INT is ignored on background tasks as [suggested here](https://stackoverflow.com/a/45106961). – LMC Apr 13 '18 at 15:58

1 Answers1

0

Unfortunately it is answer only for last question, but someone could use it.

To cleanup this trapping signal should work:

trap 'kill -TERM -$$' EXIT

On EXIT of script it is sending TERMINATE signal to its group (-$$). All processes with gpid same as main process pid will be terminated then.

PS. I still don't know why only one sleep responds to INT signal and why it's happening.

ravenwing
  • 668
  • 3
  • 20