首页 > 解决方案 > 在 ksh 脚本中获取数组中的 pid

问题描述

我正在使用 ksh 创建一个脚本,其中执行一个进程 (simple_script.sh) 并迭代 5 次。我需要做的是每次执行进程时获取 pid 并将它们存储在数组中。到目前为止,我可以让脚本执行 simple_script.sh 5 次,但无法将 pid 放入数组中。

while [ "$i" -lt 5 ]
do
        ./simple_script.sh
        pids[$i]=$!
        i=$((i+1))
done

标签: arraysshellksh

解决方案


正如 Andre Gelinas 所说,$!存储最后一个后台进程的 pid。

如果你对所有并行执行的命令都满意,你可以使用这个

#!/bin/ksh

i=0
while [ "$i" -lt 5 ]
do
        { ls 1>/dev/null 2>&1; } &
        pids[$i]=$!
        i=$((i+1))
        # print the index and the pids collected so far
        echo $i
        echo "${pids[*]}"
done

结果将如下所示:

1
5534
2
5534 5535
3
5534 5535 5536
4
5534 5535 5536 5537
5
5534 5535 5536 5537 5538

如果要串行执行命令,可以使用wait.

#!/bin/ksh

i=0
while [ "$i" -lt 5 ]
do
        { ls 1>/dev/null 2>&1; } &
        pids[$i]=$!
        wait
        i=$((i+1))
        echo $i
        echo "${pids[*]}"
done

推荐阅读