0

我有这个:

#!/bin/sh

handle_exit()
{
    # if func2 called first then do some thing to kill func1 also 
    # if func1 called first then do some thing to kill func2 also 

    exit
}

func1()
{
    for i in `seq 40`
    do
        echo I am in func1 $i
        sleep 3

        if [ "$i" = "20" ] ; then # this could be a failure condition
            handle_exit 
        fi
    done
}

func2()
{
    for i in `seq 40`
    do
        echo I am in func2 $i
        sleep 3

        if [ "$i" = "10" ] ; then # this could be a failure condition
            handle_exit             
        fi
    done
}

func1 &

pidfunc1=$!

func2 &

pidfunc2=$!

我希望它如何表现:

  1. 调用 func1 和 func2 作为子进程。(已经这样做了)
  2. 如果在运行时发生错误func1,则调用handle_exitwhich shouldexit func1kill func2
  3. 与 #2 相同,但用于 func2。如果在运行时发生错误func2,则调用handle_exitwhich shouldexit func2同时终止 func1

你能帮我吗?

4

1 回答 1

-1

将以下内容放在脚本的开头:

pidfunc1=0;
pidfunc2=0;

handle_exit()
{

    if [ "pidfunc1" != "0" ] ; then
            kill -9 $pidfunc1
            echo "killed 1"
    fi
    if [ "pidfunc2" != "0" ] ; then
            kill -9 $pidfunc2
            echo "killed 2"
    fi

}
于 2012-06-18T21:59:52.430 回答