How to use fork() in Perl?

I have hundreds of file names in an array. I want to create a child process for every 4 files in the array, and have that child do some stuff to each of those 4 files. (So with 100 files, I'll create 25 processes.)

I'm having some trouble understanding the order in which lines are processed when there's a fork. I was thinking I could do something like this, but I'm getting stuck:

foreach $file (@files) {
 if ($f++ % 4 == 0) {
  my $pid = fork();

  if ($pid) {
   push(@childs, $pid);
  }
  elsif ($pid == 0) {
    ... do stuff to $file ...
  }
 }

I don't think this is right, and I'm hoping someone can point me in the right direction. Thanks.

Answers


In addition to your trouble using fork, you also seem to have trouble partitioning your @files array into smaller sets of four files. Maybe something like this:

for (my $i = 0; $i < @files; $i += 4) {

    # take a slice of 4 elements from @files
    my @files4 = @files[$i .. $i + 3];

    # do something with them in a child process
    if (fork() == 0) {
        ... do something with @files4 ...
        exit;   # <--- this is very important
    }
}

# wait for the child processes to finish
wait for 0 .. @files/4;

Need Your Help

MySQL data structure vs. calculated data for Checkbox type data

php mysql data-structures boolean boolean-operations

Assuming you have a multiple boolean fields within a common category, which database storage method is more efficient for both speed and processing (for both MySQL and PHP)?

Rails 3.1 and sprockets make it harder to debug using firebug?

ruby-on-rails ruby-on-rails-3 sprockets

In Rails 3.1, Sprockets are used to manage assets and package them into a single file. Which, in general, is not such a bad idea.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.