I am currently building a Laravel app that should start external processes and then monitor their status using the process ID.
The processes are started like this, returning the pid:
exec('nohup <script> & echo $!');
This works fine. But now I have problems tracking the status of the newly started process, presumably because the methods I use require the checked process to be a child process of the shell executing the commands.
Currently I try to determine if the process is still running by:
exec("ps -p $pid -o pid=") == $pid;
This retruns true
if the process is still running but works only with child processes. I should be able to use kill -0 <pid>
here instead, so this is not a big problem.
What is the problem, though, is determining the exit code of the process. My current code looks like this:
exec("wait $pid; echo \$?");
When the process is finished, wait
should immediately return and write the exit code to $?
. But this also works only for child processes of the shell that executed the original command, so I always get the exit code 127
(is not a child of this shell).
Is there any other way of getting the exit code of a process?
Also, I use the same Laravel queue both for starting and monitoring the processes (with the php artisan queue:listen
command) so the exec()
methods are called from within the same process. Or does PHP start a separare shell for each exec()
call?
Edit: I know now that Laravel does start a new process for every queued command so starting the scripts and monitoring their state is done in different processes.