I have a problem, I use pcntl_fork to fork a process in PHP,
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// we are the parent
pcntl_wait($status); //Protect against Zombie children
} else {
pcntl_exec("/path/to/php/script");
echo "Could not Execute...";
}
I am trying to figure out a way to monitor the status of the PHP script executed as the Child in the parent fork. Is there any way we can know if the child is still running or if there was any fatal errors raised during the execution of the child script and to catch all the messages from the child to parent process using;
pcntl_signal(SIGUSR1, "signal_handler");
Thanks & Regards,
Arun Shanker Prasad.
You can definitely monitor the child process:
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// we are the parent
pcntl_waitpid($pid, $status, WUNTRACED); //Protect against Zombie children
if (pcntl_wifexited($status)) {
echo "Child exited normally";
} else if (pcntl_wifstopped($status)) {
echo "Signal: ", pcntl_wstopsig($status), " caused this child to stop.";
} else if (pcntl_wifsignaled($status)) {
echo "Signal: ",pcntl_wtermsig($status)," caused this child to exit with return code: ", pcntl_wexitstatus($status);
}
} else {
pcntl_exec("/path/to/php/script");
echo "Could not Execute...";
}
EDIT:
To clarify regarding messaging between parent and child process; you definitely cannot catch Exceptions across processes. As far as messaging, using only the PCNTL library you are also limited to process signals and exit codes.
Not knowing what, exactly, you are doing. You have a variety of other options. I'd suggest one of the following asynchronous messaging solutions, as they could possibly cover your needs.
File based
Your child processes could write messages to a file, which would be polled by the parent.
Memcache based
Same as above, but using memcached as the communications medium.
Database based
Same as above, but using a db table as the communications medium.
PHP's semaphore/IPC library
http://us3.php.net/manual/en/book.sem.php
This allows you to use methods like msg_send() and msg_receive() to communicate across processes.
I'm confident one of these will provide the solution you are looking for. Going into the specifics of how to use any of these methods, is probably beyond the scope of this question though, but feel free to ask a new question if you need help with whichever method you choose to utilize.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With