On Wed, May 27, 2009 at 05:42, Michael Alipio <daem0n...@yahoo.com> 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: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/