I have this:
puts pids
pids.each do |pid|
puts "Running on pid #{pid}"
begin
Process::kill(0, pid)
puts "Pid #{pid} still alive"
rescue Errno::ESRCH
puts "Pid #{pid} now dead!!!!"
pids.delete(pid)
running_jobs -= 1
puts "Remaining jobs: #{running_jobs}"
end
end
which outputs this:
25555
25579
25616
Running on pid 25555
Pid 25555 now dead!!!!
Remaining jobs: 2
Running on pid 25616
Pid 25616 now dead!!!!
Remaining jobs: 1
As you can see, the loop is never executed on the middle element. Can anyone tell me why that happens that way? I need to really loop over every item and handle it accordingly.
You are mutating the array as you iterate over it with pids.delete(pid)
So you are on 25555 at index 0, then you delete it, causing the array to look like [25579, 25616]
. Then you iterate, now you are at index 1, which is 25616. If you simply remove the delete, you will no longer be mutating the array and the iteration will work as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With