【发布时间】:2016-12-07 20:16:25
【问题描述】:
我想在 bash 中有一个函数,它在后台启动一个程序,确定该程序的 PID,并将其输出通过管道传输到sed。我知道如何分别做其中任何一个,但不知道如何同时实现所有这些。
到目前为止,我所拥有的是:
# Start a program in the background
#
# Arguments:
# 1 - Variable in which to "write" the PID
# 2 - App to execute
# 3 - Arguments to app
#
function start_program_in_background() {
RC=$1; shift
# Start program in background and determine PID
BIN=$1; shift
( $BIN $@ & echo $! >&3 ) 3>PID | stdbuf -o0 sed -e 's/a/b/' &
# ALTERNATIVE $BIN $@ > >( sed .. ) &
# Write PID to variable given as argument 1
PID=$(<PID)
# when using ALTERNATIVEPID=$!
eval "$RC=$PID"
echo "$BIN ---PID---> $PID"
}
我提取 PID 的方式受到 [1] 的启发。 cmets 中有第二个变体。当执行使用上述函数启动程序的脚本时,它们都显示了后台进程的输出,但是当我管道时没有输出
[1]How to get the PID of a process that is piped to another process in Bash?
有什么想法吗?
【问题讨论】:
-
与问题无关,但您应该将
$@放在双引号中以正确重新引用结果。 -
调用者对 PID 做了什么?如果它终止进程,它可能会在有机会向
sed发送任何内容之前终止它。 -
现在,我只是在后面加上一个
sleep 10然后杀死它,是的。但是这个过程应该有足够的时间来输出东西。我还尝试使用stdbuf -i0来确保问题与缓冲无关。 -
感谢双引号的提示!
-
您可能需要在
$BIN上使用stdbuf -o0以防止其输出到管道被缓冲。
标签: bash background pipe pid