The exec Function

Everything we’ve 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 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, the Perl process is gone,[319] only the process running the bedrock command remains. 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? 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 standing around tapping its toes waiting for the other program to complete, so Perl could finally exit as well. That’s a wasted resource.

Having said that, using exec is rare except in combination with fork (which you’ll see later). If you are puzzling over ...

Get Learning Perl, Fourth Edition 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.