如何在我的shell脚本中编写此进程查杀逻辑

时间:2012-06-18 21:15:10

标签: bash shell

我有这个:

#!/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_exitexit func1也会杀死func2
  3. 与#2相同,但对于func2。如果在func2正在运行时发生错误,请拨打handle_exitexit func2也会杀死func1
  4. 你能帮忙吗?

1 个答案:

答案 0 :(得分:-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

}