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 anymore,[‡] 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.
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 ...