Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

next element of array passed when using fork?

Status
Not open for further replies.

ajmcello

Technical User
Apr 20, 2010
7
0
0
US

I have an array with 5 elements. With each fork, I want the next element to pass to it and then exit. Here's what I've got so far. Could someone please help? :)

Here's what I get:

child 0 k: test1
child 0 k: test2
child 0 k: test3
child 0 k: test4
child 0 k: test5
child 1 k: test1
child 1 k: test2
child 1 k: test3
child 1 k: test4
child 1 k: test5
child 2 k: test1
child 2 k: test2
child 2 k: test3
child 2 k: test4
child 2 k: test5
child 3 k: test1
child 3 k: test2
child 3 k: test3
child 3 k: test4
child 3 k: test5
child 4 k: test1
child 4 k: test2
child 4 k: test3
child 4 k: test4
child 4 k: test5

Here's what I'd like it to say:

child 0 k: test1
child 1 k: test2
child 2 k: test3
child 3 k: test4
child 4 k: test5


Thanks in advance!

code:

Code:
#!/usr/bin/perl

@array = qw(test1 test2 test3 test4 test5);

$x=0;
$num = 5;

for ( 1 .. $num ) {
    my $pid = fork();
    if ($pid) {
        push( @childs, $pid );
    }
    elsif ( $pid == 0 ) {
        print "parent\n";
        sleep 5;
        exit(0);
    }
    else {
        die "couldnt fork: $!\n";
    }
}
foreach (@childs) {
        foreach $k (@array) {
                print "child $x k: $k\n";
                next;
        }
                $x++;
}
 
Don't kill the parent, you need it to spawn each child. The following is probably what you're looking for:

Code:
#!/usr/bin/perl

use strict;
use warnings;

my @array = qw(test1 test2 test3 test4 test5);

for my $test (@array) {
	my $pid = fork() // die "Couldn't fork: $!";

	if ($pid) {
		print "Child $pid starting $test\n";
		sleep 5;
		print "Child $pid ending $test\n";
		exit;
	}
}

- Miller
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top