【问题标题】:Getting pids in an array in ksh script在 ksh 脚本中获取数组中的 pid
【发布时间】:2019-03-21 00:26:45
【问题描述】:

我正在使用 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

【问题讨论】:

  • $!用于获取最后一个BACKGROUND进程的PID。因此,如果您在调用简单脚本后添加“&”,您将拥有全部 5 个 PID。

标签: arrays shell ksh


【解决方案1】:

正如 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

【讨论】:

  • 做了一些小的调整,但这无疑为我指明了我需要进入的方向。谢谢
猜你喜欢
  • 2013-06-02
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-29
  • 1970-01-01
  • 2014-10-05
相关资源
最近更新 更多