0

I have a bash function func_1 which calls func_2. func_2 does not terminate until told to via ^C. How can I terminate func_2 and then continue execution of func_1? Calling func_1 and then terminating during func_2 stops func_1. Thanks!

3
  • 1
    AFAIK there is no way to kill a function as such, you'll have to kill whatever func_2 is doing from a trap or the surrounding code. If you include the actual code it would be easier to see what would actually work. Commented Sep 30, 2019 at 5:58
  • 1
    Also, on another, unrelated note, ^C is equivalent of SIGINT (i.e. kill -2). SIGTERM is kill -15. Commented Sep 30, 2019 at 6:59
  • 1
    bash functions run in the same process as the script that calls them. and signals like ^C (SIGINT) are delivered at the process level. So, there is no way to terminate the current function without terminating the parent script. Having said that, you could TRAP the signals set some global variable and do an early exit from func_2 by detecting that variable. It will help us if you post func_2's code. Commented Sep 30, 2019 at 7:03

1 Answer 1

1

Assuming the processing in func_2 is done with external program (see sleep statement in example below), you can use 'trap' to capture the ctrl/C (actually SIGINT, as per comments above from @anishsane)

Note that explicit termination of the external process is performed by dispatching the signal to that child.

#! /bin/bash

func_1() {
        echo "In func_1"
        sleep 100 &
        # Save the PID of the external program
        X=$!
        trap 'kill -INT $X' INT
        # Wait for the external program to finish/get killed.
        wait
        echo "resume func_1"
}

func_2() {
        echo "In func_2"
        func_1
        echo "resume func_2"
}

func_2

If you can the above script, and enter "ctrl/C", the output will be:

In func_2
In func_1
^Cresume func_1
resume func_2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.