Bash 功能:在后台启动程序,确定PID和管道输出
Bash function: start program in background, determine PID and pipe output
我想在 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=; shift
# Start program in background and determine PID
BIN=; 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]的启发。评论中有第二种变体。当执行使用上述函数启动程序的脚本时,它们都显示后台进程的输出,但是当我管道
时没有输出
[1] How to get the PID of a process that is piped to another process in Bash?
有什么想法吗?
解法:
多亏了一些有用的评论,我自己想出了这个。为了能够标记为已解决,我在这里发布了工作解决方案。
# 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=; shift
# Create a temporary file to store the PID
FPID=$(mktemp)
# Start program in background and determine PID
BIN=; shift
APP=$(basename $BIN)
( stdbuf -o0 $BIN $@ 2>&1 & echo $! >&3 ) 3>$FPID | \
stdbuf -i0 -o0 sed -e "s/^/$APP: /" |\
stdbuf -i0 -o0 tee /tmp/log_${APP} &
# Need to sleep a bit to make sure PID is available in file
sleep 1
# Write PID to variable given as argument 1
PID=$(<$FPID)
eval "$RC=$PID"
rm $FPID # Remove temporary file holding PID
}
我想在 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=; shift
# Start program in background and determine PID
BIN=; 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]的启发。评论中有第二种变体。当执行使用上述函数启动程序的脚本时,它们都显示后台进程的输出,但是当我管道
时没有输出[1] How to get the PID of a process that is piped to another process in Bash?
有什么想法吗?
解法:
多亏了一些有用的评论,我自己想出了这个。为了能够标记为已解决,我在这里发布了工作解决方案。
# 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=; shift
# Create a temporary file to store the PID
FPID=$(mktemp)
# Start program in background and determine PID
BIN=; shift
APP=$(basename $BIN)
( stdbuf -o0 $BIN $@ 2>&1 & echo $! >&3 ) 3>$FPID | \
stdbuf -i0 -o0 sed -e "s/^/$APP: /" |\
stdbuf -i0 -o0 tee /tmp/log_${APP} &
# Need to sleep a bit to make sure PID is available in file
sleep 1
# Write PID to variable given as argument 1
PID=$(<$FPID)
eval "$RC=$PID"
rm $FPID # Remove temporary file holding PID
}