The first point to consider will be codiac's comment: why do you need to run your processes in the background (the & at the end of your system() calls).

If you do need these ampersands it means you have to wait()/waitpid() on them to finish. Otherwise you seriously run the risk of your perl program reaching its end and terminating while your sub-processes spawned with system() have not yet finished.

So, the pattern would be: obtain the PID of each spawned command and waitpid() for it. When waitpid() has returned, it means process with that PID has finished and you then print your messages.

A good question would be how to get the PID of the command spawned by system(). A suggestion can be found in marufcetin's comment and also in this node http://www.perlmonks.org/?node_id=680938 which has this:

my $pid = open my $cmd, "-|", 'ls -al' or die $!;

Note: "If the "open" involved a pipe, the return value happens to be the pid of the subprocess.", from the perlfunc manual.

Alternatively, the "purest" way would be to fork() first and system() within, without the ampersands. Then, all you have to do is to wait on the forked pid. This is demonstrated in this node: http://www.perlmonks.org/?node_id=671047

And if all these forks look scary, you can use a high level module such as Parallel::ForkManager or similar (e.g. Parallel::Simple) to spawn your system() commands without the ampersands and wait for them to finish.

However, from the code you supplied it looks to me that you can improve on your design a lot especially those ampersands...


In reply to Re: Executing a command after the preceding command finished processing by bliako
in thread Executing a command after the preceding command finished processing by Locutus_

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.