在bash文件中收集并行进程的进程ID [英] Collecting process ids of parallel process in bash file
问题描述
下面,我有一个脚本,该脚本收集单个命令的进程ID,并将它们附加到bash中的数组中.由于某些原因,您可以在下面看到stdout,最终结果数组仅包含一项,即最新ID.该脚本末尾的结果PROCESS_IDS
数组如何包含所有四个进程ID?
Below I have a script that is collecting the process ids of individual commands, and appending them to an array in bash. For some reason as you can see stdout below, the end resulting array just contains one item, the latest id. How can the resulting PROCESS_IDS
array at the end of this script contain all four process ids?
PROCESS_IDS=()
function append {
echo $1
PROCESS_IDS=("${PROCESS_IDS[@]}" $1)
}
sleep 1 && echo 'one' & append $! &
sleep 5 && echo 'two' & append $! &
sleep 1 && echo 'three' & append $! &
sleep 5 && echo 'four' & append $!
wait
echo "${PROCESS_IDS[@]}"
这是标准输出:
83873
83875
83879
83882
three
one
four
two
83882
推荐答案
不要将append
操作本身发送到后台.在要放置背景的内容中放置&
之后,在之前中放置append
就足够了:sleep
和echo
仍然是背景,但是
Don't send the append
operation itself to the background. Putting an &
after the content you want to background but before the append
suffices: The sleep
and echo
are still backgrounded, but the append
is not.
process_ids=( )
append() { process_ids+=( "$1" ); } # POSIX-standard function declaration syntax
{ sleep 1 && echo 'one'; } & append "$!"
{ sleep 5 && echo 'two'; } & append "$!"
{ sleep 1 && echo 'three'; } & append "$!"
{ sleep 5 && echo 'four'; } & append "$!"
echo "Background processes:" # Demonstrate that our array was populated
printf ' - %s\n' "${process_ids[@]}"
wait
这篇关于在bash文件中收集并行进程的进程ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!