终止另一个bash函数调用的bash函数,而不会终止调用者

问题描述 投票:0回答:1

我有一个bash函数func_1,它调用func_2。直到通过^ C通知func_2才终止。如何终止func_2,然后继续执行func_1?调用func_1,然后在func_2期间终止将停止func_1。谢谢!

bash
1个回答
0
投票

假设func_2中的处理是通过外部程序完成的(请参见下面的示例中的sleep语句,您可以使用'trap'捕获ctrl / C(实际上是SIGINT,根据@anishsane的上述注释)]

请注意,通过将信号发送给该子进程来显式终止外部进程。

#! /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

如果可以使用上面的脚本,然后输入“ ctrl / C”,则输出为:

In func_2
In func_1
^Cresume func_1
resume func_2
© www.soinside.com 2019 - 2024. All rights reserved.