在bash文件中收集并行进程的进程ID [英] Collecting process ids of parallel process in bash file

查看:139
本文介绍了在bash文件中收集并行进程的进程ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面,我有一个脚本,该脚本收集单个命令的进程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就足够了:sleepecho仍然是背景,但是不是.

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屋!

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