tommyboy has asked for the wisdom of the Perl Monks concerning the following question:
#!/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]; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Iteration problem on a tied array
by jackdied (Monk) on Oct 17, 2001 at 18:56 UTC | |
by Anonymous Monk on Oct 17, 2001 at 20:36 UTC | |
|
Re: Iteration problem on a tied array
by fokat (Deacon) on Oct 18, 2001 at 00:31 UTC |