Документация
HTML CSS PHP PERL другое

Section 14.2.  The exec Function

 
Previous
Table of Contents
Next

14.2. 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,[Section 14.2.  The exec Function] 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.

[Section 14.2.  The exec Function] 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? 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 system versus exec, pick system, and you'll be fine most of the time.

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: $!";

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

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

    Previous
    Table of Contents
    Next
    © 2000- NIV