bash的陷阱中断命令,但应退出环路结束 [英] bash trap interrupt command but should exit on end of loop

查看:241
本文介绍了bash的陷阱中断命令,但应退出环路结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从来就问猛砸陷阱 - 出口仅在循环的结束和提交解决方案的工作,但同时pressing CTRL-C在脚本运行命令(mp3convert与跛脚)将被打断,比完整的循环将运行到最后。让我告诉你这个简单的脚本:

I´ve asked Bash trap - exit only at the end of loop and the submitted solution works but while pressing CTRL-C the running command in the script (mp3convert with lame) will be interrupt and than the complete for loop will running to the end. Let me show you the simple script:

#!/bin/bash
mp3convert () { lame -V0 file.wav file.mp3 }

PreTrap() { QUIT=1 }

CleanUp() {
  if [ ! -z $QUIT ]; then
     rm -f $TMPFILE1
     rm -f $TMPFILE2
     echo "... done!" && exit
  fi }

trap PreTrap SIGINT SIGTERM SIGTSTP
trap CleanUp EXIT

case $1 in
     write)
           while [ -n "$line" ]
             do
                mp3convert
                [SOMEMOREMAGIC]
                CleanUp
             done
    ;;
QUIT=1

如果我preSS CTRL-C,而功能mp3convert运行瘸腿命令将被打断,然后清理运行之前[SOMEMOREMAGIC]会执行。我不明白为什么跛脚命令将被打断,我怎么能避免它们。

If I press CTRL-C while function mp3convert is running the lame command will be interrupt and then [SOMEMOREMAGIC] will execute before CleanUp is running. I don´t understand why the lame command will be interrupt and how I could avoid them.

推荐答案

尝试简化上面的讨论,我包下图显示案例脚本更容易理解的版本。该脚本还处理了双控-C的问题:
(双控-C的问题:如果你打控制c两次或者三次,这取决于有多少等待$ PID 你使用,这些清理不能正常进行。 )

Try to simplify the discussion above, I wrap up an easier understandable version of show-case script below. This script also HANDLES the "double control-C problem": (Double control-C problem: If you hit control C twice, or three times, depending on how many wait $PID you used, those clean up can not be done properly.)

#!/bin/bash

mp3convert () {
  echo "mp3convert..."; sleep 5; echo "mp3convert done..."
}

PreTrap() {
  echo "in trap"
  QUIT=1
  echo "exiting trap..."
}

CleanUp() {
  ### Since 'wait $PID' can be interrupted by ^C, we need to protected it
  ### by the 'kill' loop  ==> double/triple control-C problem.
  while kill -0 $PID >& /dev/null; do wait $PID; echo "check again"; done

  ### This won't work (A simple wait $PID is vulnerable to double control C)
  # wait $PID

  if [ ! -z $QUIT ]; then
     echo "clean up..."
     exit
 fi
}

trap PreTrap SIGINT SIGTERM SIGTSTP
#trap CleanUp EXIT

for loop in 1 2 3; do
    (
      echo "loop #$loop"
      mp3convert
      echo magic 1
      echo magic 2
      echo magic 3
    ) &
    PID=$!
    CleanUp
    echo "done loop #$loop"
done

杀-0 招可以在此链接

这篇关于bash的陷阱中断命令,但应退出环路结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆