Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 837
sid_com Avatar asked Apr 26 '10 06:04

sid_com


People also ask

How do I run a command in the background?

If you want to run additional commands while a previous command runs, you can run a command in the background. If you know you want to run a command in the background, type an ampersand (&) after the command as shown in the following example. The number that follows is the process id.

How do I run a system command in Perl?

From Perl HowTo, the most common ways to execute external commands from Perl are: my $files = `ls -la` — captures the output of the command in $files. system "touch ~/foo" — if you don't want to capture the command's output. exec "vim ~/foo" — if you don't want to return to the script after executing the command.

Which command will make process to run in background in bash?

Use bg to Send Running Commands to the Background You can easily send these commands to the background by hitting the Ctrl + Z keys and then using the bg command. Ctrl + Z stops the running process, and bg takes it to the background.


1 Answers

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().

like image 168
Grant McLean Avatar answered Oct 27 '22 02:10

Grant McLean