maa has asked for the wisdom of the Perl Monks concerning the following question:
Hi, folks
ActivePerl's fork emulation has much improved in perl 5.8.4 and I've been testing it on NT and have received some 'surprising' results.
My input file was 10_000 lines long, one 'computername' per line of the form computer00001, computer00002 etc. The script spawns (correctly) ten threads which each read from the file then prints it to a results file with the PID of the thread.
All 10_000 computernames are in the results file, in order with no duplicates. What surprised me was that each thread appears to process 256 consecutive lines from the input file even though the threads all 'take a turn'. It's not important but I wondered if anyone could shed any light on why it would do that?
When the output is shown on STDOUT each thread is takings its turn but jumping around the file, rather than taking sequential lines... not what I expected to see at all.
#!C:/ActivePerl5.8.4/bin/perl.exe use strict; use warnings; require 5.8.4; #We only run if we're using Perl v5.8.4 $|++; #Unbuffer I/O my @pids=(); my $parentpid=$$; my $pid; print "The parents PID -s $parentpid\n"; my $thread_counter=0; my $testinput = "C:/Logchecks/test/forklist.txt"; my $testoutput = "C:/Logchecks/test/forkresults.csv"; open (IN,"<$testinput") or die("can't open input file $!\n"); open (OUT,">$testoutput") or die ("can't open output file $!\n"); OUTER: for (1..10) { $thread_counter++; $pid=fork(); if ($pid==0) { #child @pids=(); $pid=$$; $parentpid=0; last OUTER; }else{ push @pids,$pid; print "Parent has spawned child $pid\n"; } } if ($parentpid == 0) { #kid my $items=0; while (my $cname= <IN> ) { chomp $cname; $items++; print "$cname checked by $$\n"; print OUT "$cname,checked by $$\n"; sleep 1; } print "Thread $$ processed $items items.\n"; exit(0); } else { #parent print "$thread_counter threads started - waiting on completion.\n"; Reaper(); print "Parent: Goodbye(:-)\n"; exit(0); } sub Reaper { while (my $kid = shift(@pids)) { #warn "$$ to reap $kid\n" ; my $reaped = waitpid($kid,0); unless ($reaped != -1) { warn "waitpid $reaped: $?\n" ; } } }
Thanks in advance - Mark
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Unexpected output from fork (Win32)
by BrowserUk (Patriarch) on Aug 09, 2004 at 11:58 UTC | |
by maa (Pilgrim) on Aug 09, 2004 at 14:03 UTC | |
|
Re: Unexpected output from fork (Win32)
by Jenda (Abbot) on Aug 09, 2004 at 12:51 UTC | |
by maa (Pilgrim) on Aug 09, 2004 at 14:25 UTC | |
by BrowserUk (Patriarch) on Aug 09, 2004 at 17:51 UTC | |
by Jenda (Abbot) on Aug 09, 2004 at 16:27 UTC | |
by iburrell (Chaplain) on Aug 09, 2004 at 16:46 UTC | |
by maa (Pilgrim) on Aug 09, 2004 at 17:38 UTC | |
|
Re: Unexpected output from fork (Win32)
by tachyon (Chancellor) on Aug 09, 2004 at 11:23 UTC | |
by maa (Pilgrim) on Aug 09, 2004 at 12:00 UTC |