在shell脚本

时间:2017-05-23 16:13:46

标签: bash signals

我想运行带有监视程序的进程,如果它们崩溃会重启它们。为此,我有以下配置文件和process.sh:

$ cat process.sh 
#!/bin/bash

sleep $1;
exit -1

$ cat processes.cfg 
slow:./process.sh 5
fast:./process.sh 3

以下脚本读取processes.cfg并使用process.sh启动子进程。我写了以下

https://serverfault.com/questions/52976/simple-way-of-restarting-crashed-processes

#!/bin/bash

wtch () {

  until eval "$1" ; do
    echo "server '$2' crashed with exit code $? . respawning ..." >&2
    sleep 1
  done
}

cleanup () {

  echo killing subprocesses ...

  for i in "${!subproc[@]}"
  do
    echo killing ${subproc[$i]}
    kill -9 ${subproc[$i]}
  done

  echo exiting ...
  exit -1
}

declare -A subproc

cat processes.cfg | while IFS=: read name command
do
  echo "$command" "$name"
  wtch "$command" "$name" &
  subproc[$name]=$!
  echo $!
done

trap cleanup SIGINT

while true; do
  sleep 10;
done

现在,点击ctrl-c不会像我期望的那样杀死子进程。由于某些原因,cleanup函数在子进程数组中找不到任何内容。

这是因为信号处理程序没有看到subproc数组吗?

我该如何使这项工作?我为了测试而做了这个信号处理程序,手动清理看门狗进程很乏味。

1 个答案:

答案 0 :(得分:1)

这是因为while […] done < processes.cfg修改发生在子shell 中,由piping into a while loop引起。相反,您可以while将{{1}}循环保留在同一个shell中。