O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

14.1. Using system and exec

When you give the shell a command line to execute, the shell usually creates a new process to execute the command. This new process becomes a child of the shell, executing independently, yet coordinating with the shell.

Similarly, a Perl program can launch new processes, and like most other operations, has more than one way to do so.

The simplest way to launch a new process is to use the system function. In its simplest form, this function hands a single string to a brand new /bin/sh shell to be executed as a command. When the command is finished, the system function returns the exit value of the command (typically 0 if everything went OK). Here's an example of a Perl program executing a date command using a shell:[1]

system("date");

[1] This doesn't actually use the shell: Perl performs the operations of the shell if the command line is simple enough, and this one is.

We're ignoring the return value here, but it's not likely that the date command is going to fail anyway.

Where does the command's output go? In fact, where does the input come from, if it's a command that wants input? These are good questions, and the answers to these questions are most of what distinguishes the various forms of process-creation.

For the system function, the three standard files (standard input, standard output, and standard error) are inherited from the Perl process. So for the date command in the previous example, the output goes wherever the print STDOUT output goes—probably ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required