How to spawn other programs within perl script and immediately continue Perl processing (instead of halting until the spawned program terminates) ? Is it possible to process the output coming from the spawned program while it is running instead of waiting it to end?
-
[Perl FAQ 8: How do I start a process in the background?](http://learn.perl.org/faq/perlfaq8.html#How-do-I-start-a-process-in-the-background-), http://stackoverflow.com/questions/2711520/how-can-i-run-perl-system-commands-in-the-background, http://stackoverflow.com/questions/2133910/how-can-i-fire-and-forget-a-process-in-perl – daxim Nov 17 '11 at 10:14
2 Answers
You can use open
for this (to run the program /bin/some/program
with two command-line arguments):
open my $fh, "-|", "/bin/some/program", "cmdline_argument_1", "cmdline_argument_2";
while (my $line = readline($fh)) {
print "Program said: $line";
}
Reading from $fh
will give you the stdout of the program you're running.
The other way around works as well:
open my $fh, "|-", "/bin/some/program";
say $fh "Hello!";
This pipes everything you write on the filehandle to the stdin of the spawned process.
If you want to read and write to and from the same process, have a look at the IPC::Open3
and IPC::Cmd
modules.

- 1,620
- 9
- 18
To run a program in the background and "continue going" all you have to do is add "&" at the end of the command (I'm assuming you are using Linux). example:system("command &");
note that system("command", "arg1", "&");
will NOT work, since it will pass the "&" to the command and not to the shell. You can simply print the output of a command by doing: print system("command");

- 887
- 2
- 8
- 16
-
When you down vote write a comment why it is not useful. I think this is a valid answer because there were two questions, one is to process the output other is to continue the rest of the code without waiting for the command to finish. I will be glad to know the reason if i am wrong – SAN Nov 17 '11 at 05:41
-
system() doesn't return the output of a command, but its return code/exit status. The child process inherits stdin/out/err from the process doing the call to system(). Also, I don't like to encourage people to use one-argument system() - it comes with scary security risks. – Martijn Nov 17 '11 at 05:52