To complement @DaveRandom's answer: you don't actually need to redirect STDERR
to STDOUT
(with 2>&1
).
You need to redirect STDOUT
though, if you want to prevent the parent process from hanging waiting for the child to finish. This is required cause exec
will return the last line of the output of the child process, therefore, it needs to wait for the child's STDOUT
to be closed.
That doesn't mean you need to redirect it to /dev/null
. You can redirect it to some other file, or even to some other file descriptor (like STDERR
: 1>&2
).
exec('/path/to/executable')
: will start a new process and wait for it to finish (i.e. blocking the parent process).
exec('/path/to/executable &')
: basically the same as the above.
$pid = exec('/path/to/executable > /dev/null & echo $!')
: will start a process in the background, with child and parent processes running in parallel. The output of /path/to/executable
will be discarded, and $pid
will receive the PID of the child process.
Using 2>&1
is actually not necessary, cause exec
ignores the STDERR
of the child process. It is also probably undesirable cause it will make it harder to find some errors, cause they will be just silently thrown away. If you omit 2>&1
, you can pipe the STDERR
of the parent process to some log file, that can be checked later when something goes wrong:
php /path/to/script.php 2>> /var/log/script_error.log
By using the above to start the script which triggers the child processes, everything that script.php
and any child process write to STDERR
will be written to the log file.