Book HomeLearning Perl, 3rd EditionSearch this book

14.2. The exec Function

Everything we've just said about system syntax and semantics is also true about the exec function, except for one (very important) thing. The system function creates a child process, which then scurries off to perform the requested action while Perl naps. The exec function causes the Perl process itself to perform the requested action. Think of it as more like a "goto" than a subroutine call.

For example, suppose we wanted to run the bedrock command in the /tmp directory, passing it arguments of -o args1 followed by whatever arguments our own program was invoked with. That'd look like this:

chdir "/tmp" or die "Cannot chdir /tmp: $!";
exec "bedrock", "-o", "args1", @ARGV;

When we reach the exec operation, Perl locates bedrock, and "jumps into it." At that point, there is no Perl process any more,[314] just the process running the bedrock command. When bedrock is finished, there's no Perl to come back to, so we'd get a prompt back if we invoked this program from the command line.

[314]Actually, it's the same process, having performed the Unix exec(2) system call (or equivalent). The process ID remains the same.

Why is this useful? Well, if the purpose of this Perl program were to set up a particular environment to run another program, the purpose is fulfilled as soon as the other program has started. If we'd used system instead of exec, we'd have a Perl program just standing around tapping its toes waiting for the other program to complete, just so Perl could finally immediately exit as well, and that's a wasted resource.

Having said that, it's actually quite rare to use exec, except in combination with fork (which we'll see later). If you are puzzling over system versus exec, just pick system, and nearly all of the time, you'll be just fine.

Because Perl is no longer in control once the requested command has started, it doesn't make any sense to have any Perl code following the exec, except for handling the error when the requested command cannot be started:

exec "date";
die "date couldn't run: $!";

In fact, if you have warnings turned on, and if you have any code after the exec other than a die,[315] you'll get notified.

[315]Or exit. Or if it's at the end of a block. This may change in a new release of Perl, too.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.