Sorry about the indention... must be the mail client i'm using. I need to fork because the external program I want to run inside the child runs infinitely. I want to have a timer running in the parent and after that, kill the child. Without forking, I have to do a pkill myprogname I'm reading the perlipc now.. nothing so far..
--- On Wed, 5/27/09, Chas. Owens <[email protected]> wrote: > From: Chas. Owens <[email protected]> > Subject: Re: variables gets shared to child but resets back after exiting fork > To: "Michael Alipio" <[email protected]> > Cc: "begginers perl.org" <[email protected]> > Date: Wednesday, May 27, 2009, 7:15 PM > On Wed, May 27, 2009 at 05:42, > Michael Alipio <[email protected]> > wrote: > > > > Hi, > > > > I have to run an external program but the program does > not termination on some conditions, e.g, ping, will not exit > unless you specify -c or some other circumstances. > > > > > > Now I what I want to do is: > > > > my @array; > > die "Cannot fork myprog" unless (defined my $pid = > fork) > > if ($pid==0){ > > open MYPROG, "myprog |" or die "Cant run myprog"; > > my $timeout = 0; > > while (<MYPROG>){ > > exit(0) if $timeout == 3; > > push @array, $_; > > sleep 1; > > $timeout++; > > } > > > > waitpid($pid, 0); > > print "@array\n"; > > > > > > The problem with the code above is that @array goes > back to its initial state after exiting the child. No > contents are printed. I even tried references but it didn't > work as well. > > > > If I don't use fork, I the way I would kill the > process is by doing a call to pkill. With fork, it would be > much easier with exit. However the output of external > program gets discarded. > > > > Can you think of any workaround for this? > snip > > > Variables are not shared between parent and child. > The values of the > parent's variables are copied to the child at the time of > the fork. > You really need to read perldoc perlipc[1]. And you > need to learn how > to indent code. Leaving your code all against the > left side of the > screen makes it hard to read. > > Of course, the biggest question is why are you bothering to > fork in > the first place? Why not just say > > my $program = "myprog"; > > open my $pipe, "-|", $program > or die "Cant run $program: $!"; > > my @array; > for (1 .. 3) { > last unless defined(my $line = > <$pipe>); > push @array, $line; > } > > close $pipe; > > > > 1. http://perldoc.perl.org/perlipc.html > > -- > Chas. Owens > wonkden.net > The most important skill a programmer can have is the > ability to read. > -- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected] http://learn.perl.org/
