0

Well I'm new to programming Perl (or any language in general) I have basic understandings of the language and have written a small script that runs multiple forked threads of my processes here's a snippet of the script.

use Perl6::Slurp;
use Parallel::ForkManager;

my $pm = Parallel::ForkManager->new(10);
my $time = 100;

alarm("$time");

for my $i (0 .. 100) {
  my $pid = $pm->start and next;
  job();
  $pm->finish;
}
$pm->wait_all_children;

sub job {
  print "Function Started On Thread";
}

Now, that's not my actual code. but its pretty much a summary of what it is without the function I would like it to end when the alarm ends.

Now i don't know if this is a simple action, but as i said im really new to programming in general. Thanks for anyone that helps!

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • It's a bit hard to tell from your code what you actually want, since it seems to contains some inconsistencies (e.g. is `attack` meant to be `job`?). Do you mean that you want _all_ the subprocesses to terminate when the alarm goes off? Or do you just want to limit the time used by each individual subprocess? – Ilmari Karonen Jan 09 '14 at 11:30
  • Oh sorry about that, i didn't realize that i changed it, yes attack and job are suppose to be the same, and i want all child processes to die at the end of the alarm (So the whole script kills itself pretty much) – Taylor Smyth Jan 09 '14 at 11:39
  • You might also see http://stackoverflow.com/questions/2839824/how-should-i-clean-up-hung-grandchild-processes-when-an-alarm-trips-in-perl and [Stop fork in Parallel::ForkManager](http://www.perlmonks.org/?node_id=797554) – brian d foy Jan 09 '14 at 13:58
  • Re "`alarm("$time");`", Why would you convert `$time` to a string before passing it to `alarm`, forcing `alarm` to convert it back to a number? `alarm($time)` – ikegami Jan 09 '14 at 14:01
  • `for my $i (0..100)` is confusing `for my $i (1..101)` would be clearer and `for (1..101)` clearest if the actual values of `$i` don't matter. – ikegami Jan 09 '14 at 14:02

1 Answers1

1

Send a signal to the process group. Just add the following to the parent:

local $SIG{ALRM} = {
   local $SIG{TERM} = 'IGNORE';
   kill TERM => -$$;
   die "Timed out\n";
};
ikegami
  • 367,544
  • 15
  • 269
  • 518