是否可以跟踪在后台运行的进程的PIPESTATUS? [英] Is PIPESTATUS of processes running in background trackable?

查看:56
本文介绍了是否可以跟踪在后台运行的进程的PIPESTATUS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

扩展

Extending the question as suggested by Cyrus, I wanted to know if I could track the same script with PIPESTATUS or something similar if I sent it to run in background?

bash脚本如下:

#! /bin/bash

{ python script.py 2>&1  | tee logfile.log; } &
ret="${PIPESTATUS[0]}"
if [[ "$ret" -ne "0" ]]; then
  echo "$ret"
fi

script.py 是:

print("hello")
exit(1);
print("world")

当我在没有& 的情况下运行 bash 脚本时,它会正确打印 PIPESTATUS ,但是如果我在后台运行它,则不会输出返回.

When I run the bash script without & it prints the PIPESTATUS correctly but in case when I run it in background, no output is returned.

推荐答案

首先,正如Kamil Cuk所说,如果要后台进程的管道状态,则需要:

First off, as Kamil Cuk said, if you want the pipestatus of a background process, you need:

{ python script.py 2>&1  | tee logfile.log; exit "${PIPESTATUS[0]}" }

但是,由于您正在后台运行某些内容,因此 if 语句可能会在完成之前运行,那么您希望它测试什么返回值?

But since you're running something in the background, your if statement will probably run before it's even completed, so what return value do you expect it to test?

您通常想要的是在后台运行某些东西,做一堆工作,然后等待执行后台任务,然后再检查其返回值.

What you typically want is to run something in the background, do a bunch of work, then wait for the background task, and only then checking its return value.

wait 将返回后台shell的退出状态,因此这是实际获取由 exit"$ {PIPESTATUS [0]}" 生成的退出代码的方法.

wait will return the exit status of the background shell, so that's the way to actually get the exit code generated by exit "${PIPESTATUS[0]}"

这篇关于是否可以跟踪在后台运行的进程的PIPESTATUS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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