Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: multiple fork()

by Rhandom (Curate)
on Apr 16, 2001 at 22:37 UTC ( #72894=note: print w/replies, xml ) Need Help??


in reply to multiple fork()

If you want something simple and light, here is some code that should take care of you
#!/usr/bin/perl use IO::Select; use IO::Pipe; my $select = IO::Select->new(); my @commands = ("echo 1", "echo 2", "echo 3", "echo 4", "echo 5", ); foreach ( @commands ){ my $pipe = IO::Pipe->new(); my $pid = fork; die "Bad Fork $!" unless defined $pid; ### parent if( $pid ){ $pipe->reader(); $select->add( $pipe ); ### child }else{ $pipe->writer(); $pipe->autoflush(1); print $pipe "PID $$: COMMAND $_\n"; print $pipe `$_`; # do the command exit; } } my $num = 0; while( my @responses = $select->can_read(0) ){ die "Timedout [$!]\n" unless @responses; my $pipe = $responses[ rand @responses ]; print STDOUT while <$pipe>; print "------------------------------------------------\n"; $select->remove( $pipe->fileno() ); last if ++$num >= @commands; }
Using pipes to do all of the dirty work of IPC is great. Whoever made IO::Pipe and IO::Select (Graham Barr i think) made life wonderful. change @commands to whatever you want and you are done.

Replies are listed 'Best First'.
Re: Re: multiple fork()
by Rhandom (Curate) on Apr 16, 2001 at 23:10 UTC
    Oh - yeah, I didn't do anything with catching $SIG{CHLD} - There is the potential that you'll have zombie children until the parent process is done, but, once its done, they are gone too so I would worry about them too much unless the parent is a long, long running daemon.

      Don't catch $SIG{CHLD} as each catch gives your program about a 1% chance of die'ing since Perl's signal handlers aren't safe. See "perldoc -f waitpid" for how to reap children without catching signals.

              - tye (but my friends call me "Tye")
        Says tye:
        each catch gives your program about a 1% chance of die'ing
        Is that number "1%" actually based in reality, or did you just make it up out of your head?

        Happy Bicycle Day!

        --
        Mark Dominus
        Perl Paraphernalia

        My bad. Catch may have been misleading. I generally do things like
        use POSIX (); $SIG{CHLD} = \&sig_chld; sub sig_chld { 1 while (waitpid(-1, POSIX::WNOHANG()) > 0); $SIG{CHLD} = \&sig_chld; }
        In my terminology, this is catching the SIG CHLD. I haven't had any trouble with this sort of setup under some extremely heavy loads.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://72894]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2021-09-20 21:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?