【问题标题】:Check exit status of two parallel running background command in shell script检查 shell 脚本中两个并行运行的后台命令的退出状态
【发布时间】:2013-01-24 06:45:56
【问题描述】:

假设我在 shell 脚本中并行运行两个命令,示例如下

/cmd1 &  
pid1=$!

/cmd2 &  
pid2=$!

status1=    # what should go here?

status2=$?  # I know this will have status of previous background process only

只有当两个命令都具有干净的退出状态时,我才想继续 如何检查第一个后台进程的状态。

【问题讨论】:

    标签: shell process background exit status


    【解决方案1】:

    这位先生怎么样

    monitor ()
    {
      if ! $*
      then
        > error
      fi
    }
    
    clean()
    {
      rm -f error
    }
    
    clean
    monitor cmd1 &
    monitor cmd2
    
    if [ -a error ]
    then
      echo error encountered
      exit
    fi
    

    【讨论】:

      【解决方案2】:

      一种解决方案是使用带有 --joblog 的 GNU Parallel,这里显示了两个命令 exit 0exit 1

      (echo exit 0; echo exit 1) | parallel --joblog /tmp/foo
      cat /tmp/foo
      Seq     Host    Starttime       Runtime Send    Receive Exitval Signal  Command
      1       :       1359451838.09   0.002   0       0       0       0       true
      2       :       1359451838.093  0.002   0       0       1       0       false
      

      Exitval 列将给出退出值。如果其中一项作业失败,GNU Parallel 也会返回非零值:

      (echo exit 0; echo exit 1) | parallel && echo Do this if none fail
      

      或等价物:

      parallel ::: "exit 0" "exit 1" && echo Do this if none fail
      

      Learn more

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-01
        • 1970-01-01
        • 2013-01-05
        • 2012-01-06
        • 2013-07-28
        • 2018-07-01
        • 1970-01-01
        相关资源
        最近更新 更多