Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re^2: exec function does not return command prompt

by kbrannen (Beadle)
on Aug 15, 2014 at 19:01 UTC ( [id://1097609]=note: print w/replies, xml ) Need Help??


in reply to Re: exec function does not return command prompt
in thread exec function does not return command prompt

Better yet, if you're going to try to do something with multiple children, here's an example to speed you up. Create a file for input with a number of sleep commands with random values, then test.

#!/usr/bin/perl # multi.pl # usage: multi.pl [max_tasks] < job_list # max_task defaults to 4 # # do all the jobs as quickly as possible in parallel, but no more than # max_tasks at a time. use warnings; use strict; sub mysystem { my $cmd = shift; my $pid; #print "forking: $cmd\n"; if (($pid = fork()) == 0) { exec($cmd); } # child return $pid; # parent } # how many tasks can we do at once my $max_tasks = 4; if (defined($ARGV[0])) { $max_tasks = shift(@ARGV); } # num of curr tasks my $num_tasks = 0; # pids running, and command run my %pids = (); my ($pid, $cmd); # read tasks while ($cmd = <>) { chomp($cmd); # execute the task print "starting: $cmd\n"; $pid = mysystem($cmd); #print "forked pid $pid\n"; $pids{$pid} = $cmd; $num_tasks++; # if we're doing all we should, wait for 1 to end while ($num_tasks >= $max_tasks) { $pid = wait(); #print "reaped pid $pid\n"; last if ($pid == -1); # error? print "finished: $pids{$pid}\n"; delete($pids{$pid}); $num_tasks--; } } # wait for all children to end while ($num_tasks > 0) { $pid = wait(); last if ($pid == -1); # error? print "finished: $pids{$pid}\n"; delete($pids{$pid}); $num_tasks--; } exit(0);
Example test file:
sleep 4 sleep 2 sleep 6 sleep 3 sleep 4 sleep 2
Test run: perl multi.pl 2 < test_file_above

Replies are listed 'Best First'.
Re^3: exec function does not return command prompt
by casman46 (Initiate) on Aug 18, 2014 at 12:28 UTC

    kbrannen: thank you for your lengthy example; it is most helpful. I will experiment with this code in the context of my project.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2024-04-20 03:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found