Chapter 14. Process Management

Using system and exec

Like the command shell, 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 command 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 dir command using a shell:

system("dir");

We’re ignoring the return value here, but the dir command is not likely to fail anyway.

Where does the command’s output go? In fact, where does the input come from, if it was a command that wanted 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 dir command in the previous example, the output goes wherever the print STDOUT output goes—probably to the invoker’s command prompt. Because you are firing off another command shell, you can change the location of the standard output using the normal I/O redirections. For example, to put the output of the directory command into a file named this_dir, something like this will work just fine:

system("dir >this_dir") && die "cannot create ...

Get Learning Perl on Win32 Systems now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.