Execute System Command and Shell from Perl

From Free Knowledge Base- The DUCK Project: information for everyone
Revision as of 09:01, 13 April 2008 by Admin (Talk | contribs)

Jump to: navigation, search

The functions open, exec, system and the operator backtick utilizes the shell to start the program whenever it's called with one argument.

Related functions also include waitpid and fork.

  • system() executes the command specified. It doesn't capture the output of the command.
  • The exec() function executes the command specified and never returns to the calling program unless it fails.
  • A command surrounded by backticks is executed and the output of the command is returned to the calling script.
  • open() lets you capture the data of a command and/or feed an external command with data generated from the Perl script.

 

system

Passes a string along to the underlying system.

Executes a system command and returns a value that is the exit status of the program as returned by the wait() call. Like exec(), system() allows you to lie to a program about its name if you use the ``system PROGRAM LIST syntax. Because system() and backticks block SIGINT and SIGQUIT, killing the program they're running doesn't actually interrupt your program.

 @args = ("command", "arg1", "arg2");
 system(@args) == 0
   or die "system @args failed: $?"

 

exec

Passes a string along to the underlying system.

The exec function executes a system command without return.

 

open

This is a way of executing process as filehandles. You can open a filehandle with pipe(s).

Use open() when you want to:

  • capture the data of a command (syntax: open("command |"))
  • feed an external command with data generated from the Perl script (syntax: open("| command"))
 #-- list the processes running on your system
 open(PS,"ps -e -o pid,stime,args |") || die "Failed: $!\n";
 while ( <PS> )
 {
   #-- do something here
 }
  
 #-- send an email to user@localhost
 open(MAIL, "| /bin/mailx -s test user\@localhost ") || die "mailx failed: $!\n";
 print MAIL "This is a test message";

 

backtick

The "backtick" is the ` character (ASCII code 96, backwards-slanted single quote, or a grave accent without the character). By quoting a command string with backticks the command is processed by the system and whatever is on stdout ends up where the quoted expression is within the Perl program.

Using backtick is not exactly the same as using system(). Backtick and open will gather the program's STDOUT, while system will not.

This works with any commands that can be run from the shell, or in Perl it can be used as the argument to a function or part of an expression. It works in concert with pipes, as pipes redirect stdout to stdin, whereas backticks convert stdout to command run-time arguments.