Reputation: 265
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?
Upvotes: 1
Views: 2210
Reputation: 927
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");
Upvotes: 1
Reputation: 1620
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.
Upvotes: 6