sid_com sid_com - 2 months ago 9x
Perl Question

How can I run Perl system commands in the background?

#!/usr/bin/env perl
use warnings; use strict;
use 5.012;
use IPC::System::Simple qw(system);

system( 'xterm', '-geometry', '80x25-5-5', '-bg', 'green', '&' );

say "Hello";
say "World";

I tried this to run the xterm-command in the background, but it doesn't work:

No absolute path found for shell: &

What would be the right way to make it work?


Perl's system function has two modes:

  1. taking a single string and passing it to the command shell to allow special characters to be processed
  2. taking a list of strings, exec'ing the first and passing the remaining strings as arguments

In the first form you have to be careful to escape characters that might have a special meaning to the shell. The second form is generally safer since arguments are passed directly to the program being exec'd without the shell being involved.

In your case you seem to be mixing the two forms. The & character only has the meaning of "start this program in the background" if it is passed to the shell. In your program, the ampersand is being passed as the 5th argument to the xterm command.

As Jakob Kruse said the simple answer is to use the single string form of system. If any of the arguments came from an untrusted source you'd have to use quoting or escaping to make them safe.

If you prefer to use the multi-argument form then you'll need to call fork() and then probably use exec() rather than system().