简体   繁体   中英

Getting pids in an array in ksh script

I am creating a script using ksh where a process (simple_script.sh) is executed and iterates 5 times. What I need to do is get the pid each time the process is executed and store them in an array. So far I can get the script to execute simple_script.sh 5 times,but have been unable to get the pid's into an array.

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

As Andre Gelinas said, $! stores the pid of the last backgrounded process.

If you are okay with all of the commands executing in parallel, you can use this

#!/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

And the result will look something like this:

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

If you want to execute the commands serially, you can use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM