Let's say there is a simple script named action.sh:

echo -n 'a' | nc a.b.c.d p

action.sh here puts an a character to a.b.c.d address.

However, nc can hang sometimes, and I want to kill it:

$ ./action.sh

This works fine, no zombies left.

When I put this into background and try to terminate it, nc stays alive and I need to clean up manually:

& ./action.sh &
[1] 28747
& kill -15 28747 //here nc is still running! I have to find its PID and terminate it

Is there a way to ask action.sh to terminate nc too when it receives a termination signal?


trap ctrl_c INT

function ctrl_c() {
    # redirect to stderr to avoid showing errors in case nc isn't found
    kill -9 $(pgrep nc) > /dev/null 2>&1

echo -n 'a' | nc a.b.c.d p
  • 1
    It would add much to your answer if you gave a brief explanation. – Seamus Aug 23 '20 at 23:41
  • The kill+pgrep combo is better written with pkill. Also note that the name of the function is misleading as you don't send SIGINT to the process. – Kusalananda Aug 24 '20 at 4:12

This is also achievable by calling kill as below:

kill 15 -28747

15 is the termination signal (use 9 for kill), and 28747 is the PID of the parent process in my question.

  • 1
    Are you sure you didn't flip those? I think it should be kill -15 28747...? – Jeff Schaller Sep 13 '20 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.