簡體   English   中英

在ksh腳本中獲取數組中的pids

[英]Getting pids in an array in ksh script

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM