#!/usr/bin/perl #Package Nanny provides methods to tie an array. #The methods fill a tied array with the pids of the #non zombie children of the current proccess in real time. #I can't seem to get iteration to work. #example code: Make a few eternally looping kids, get pids. tie my @kids, 'Nanny'; if($pid = fork) { push @pids,$pid; if($pid = fork) { push @pids,$pid; if($pid = fork) { push @pids,$pid; } else{while(1){}} } else{while(1){}} } else{ exit; } if ($pid){ print "supposed number:". @pids. " real time number:".scalar @kids + ."pids @kids"; } #this does not work # for(1..@kids){ # waitpid($kids[$_],0); # } #and this doesn't either # foreach(@kids){ # waitpid($_,0); # } # #and not this either #foreach(@kids){ # print $_; # } #Nanny package: package Nanny; use Tie::Array; use strict; our @ISA = ('Tie::StdArray'); sub TIEARRAY{ my ($self) = shift; my @real_pids; bless \@real_pids, $self; return \@real_pids; } sub FETCHSIZE { my ($self) = shift; my $masterpid = $$; my @real_pids; open(PS,"ps -e -o ppid -o pid -o tty -o comm | "); my $l; while(<PS>){ $l++; next if $l == 1; my @procs = split(' ',$_); next if (defined($procs[3]) && $procs[3] eq 'ps'); if ($procs[0] == $masterpid && $procs[2] =~ /\?/) { waitpid($procs[1],0); next; } if ($masterpid == $procs[0]){ push @real_pids,$procs[1]; } } close PS; return scalar @real_pids ; } sub FETCH { my ($self,$idx) = shift; unless(defined $idx){ $idx = 0; } my $masterpid = $$; my @real_pids; open(PS,"ps -e -o ppid -o pid -o tty -o comm | "); my $l; while(<PS>){ $l++; next if $l == 1; my @procs = split(' ',$_); next if (defined($procs[3]) && $procs[3] eq 'ps'); if ($procs[0] == $masterpid && $procs[2] =~ /\?/) { waitpid($procs[1],0); next; } if ($masterpid == $procs[0]){ push @real_pids,$procs[1]; } } close PS; return $real_pids[$idx]; }
In reply to Iteration problem on a tied array by tommyboy
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |