Running programs in the current process space

int pcntl_exec ( string path [, array args [, array envs]])

We already went over the various common ways to execute programs from PHP, so you're forgiven if you thought, "what? Another to run programs?!"

However, the pcntl_exec() function is quite unlike the functions we looked at previously. Try running this script, for example:

    print "Before\n";
    print "After\n";

What do you think that should output? If you thought it would print "Before" followed by your computer's uptime information, then "After", you are quite wrong!

You see, unlike functions such as exec() or passthru(), pcntl_exec() replaces the existing process with the new program specified in its parameter. This program is launched and run normally, it has the same PID as PHP had before it called pcntl_exec(), but it replaces the PHP process entirely. As a result, the second print line is never reached, because the PHP interpreter gets killed and replaced by the uptime program in the same process.

If you find this confusing, do not despair - pcntl_exec() is very rarely used, and, to be honest, when you do need to use it things will become clear!

Author's Note: If you are a Unix programmer, it may be helpful for you to know that pcntl_exec() is just a thin wrapper around the execve() function.

The last two parameters to this function allow you to control how the launched process operates. The "args" parameter is simply an array of strings to pass into the program as arguments, whereas the "envs" parameter lets you specify environment variables and their values as an array. Use array keys for environment variables and array values for the environment values.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Piping between processes >>

Previous chapter: Other ways to evaluate pcntl_waitpid()'s return value

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.