How do I know when to use each of the execution functions?

9

How each of the PHP functions works:

  • pcntl_exec('/caminho/executar');
  • exec('/caminho/executar');
  • shell_exec('/caminho/executar');
  • Is there any uniqueness among the 3 examples mentioned above?

    Although it is clear that exec() is to execute program directly, shell_exec() can also execute a program through command line, and pcntl_exec() that also runs program, but it has something to do with process , which I did not quite understand.

    The PHP documentation did not direct me very well to understand these differences: pcntl_exec , exec and shell_exec .

        
    asked by anonymous 03.12.2015 / 18:13

    1 answer

    9

    In addition to the 3 you mentioned, there is still passthru and system for path execution.

    • pcntl_exec Creates a process separate from the main process with the command executed, still allows arguments to be set and other settings as to which user to execute this process (only if you have as root), it is developed for UNIX systems and can not be used in webservers, only in php executed via command line (CLI). It is very useful if you are developing an application that needs to manage the workspaces and which user delegates the process. The detail is that this function is part of the PCNTL extension: link
    • exec Only returns the last line generated by the output of the specified program execution.
    • shell_exec Returns all output of the command when it has finished executing.
    • system Execute immediately displaying the output, it is used to display texts.
    • passthru Also returns the output immediately however it is used to display the binary data. passthru displays the "raw data" directly to the browser.

    With both commands exec and shell_exec it is possible to capture output, while system and passthru will not let you customize and immediately display the output.

    The pcntl_exec was necessary when we need to create a block of code that runs asynchronously to the main request, compatible only when php is running in fast-cgi or php-fpm, apache_handler will not work. It allows you to do a "branch" where your code follows 2 paths based on an if, one within the "child" process and another one in the "parent" process.

        
    03.12.2015 / 18:57