convenientstore has asked for the wisdom of the Perl Monks concerning the following question:

Hello monks,
I wanted to launch 2 external programs from perl script at the sametime and problem I ran into is that when parent and child is done running 2 external program, subsequent lines gets executed twice.( I used system command ). since I wanted to just run subsequent command once , i tried using system(parent) and exec(for child).. it looks like program worked but not sure if this is the right way to do things like this... Please advise.

ps:I am not sure about wait command as when i monitor the process, they seem to perfectly go away without wait command

thank you.
use warnings; use strict; print "PID=$$\n"; my $child = fork(); die "Can't fork: $!" unless defined $child; sub si { my $ar = shift; print "ar is $ar\n"; } if ( $child > '0' ) { #parent process print "Parent process: PID=$$, chid=$child\n"; system("/root/program/parent_pro.pl"); } else { #child process my $ppid = getppid(); print "Child process: PID=$$, parent=$ppid\n"; #system("echo this is child"); exec("/root/program/child_pro.pl"); } print "hi how are you\n"; print "fine i am doing good\n"; si("MJ"); si("JP");

Replies are listed 'Best First'.
Re: using system and exec in same script using child
by ikegami (Patriarch) on Jan 11, 2010 at 06:09 UTC

    The if is executed in both the parent and the child, as made obvious by the "then" part being executed in the parent and the "else" part being executed in the child.

    So why do you think the line that follows the if would only be executed in the parent?

    exec replaces the program the process is executing with another and it never returns (except on error). So yes, using exec is appropriate since you don't want to continue executing the program int he child.

    By the way, system is a combination of fork, exec and wait or waitpid. That might fail if the child launched by fork ends before the child launched by system. You might have to avoid using system to customize the use of wait

      To add to ikegami's reply, the parent could exit before the child gets a look-in, and that would (probably) send a SIGHUP to the child and kill it. You should consider a wait or waitpid in the parent before it exits (or maybe IGNORE SIGHUP).
        so, can regular perl program have multiple sub working at sametime? Like displaying moving dots while calculating or simulatenaously launching two external program from perl script.. is that not possible? What I thought of child process is wrong as it's running the same program I am running twice.. i need ways(or at least clue) on how to do above things without running full program of it's own.