Running scripts in parallel in PHP by using an ampersand &: How do you
tell when they're all finished?
I have a PHP webpage (call it Page 1) that, upon the clicking of a button,
calls another PHP script (call it Page 2) using AJAX. Page 2 then makes a
series of calls to a Python script using the exec() function, with the ">
output.txt &" thing at the end (don't know what it's called) so the
instances of the Python script can run in parallel. After these calls are
made, Page 2 sends a success message back to Page 1.
However, since "> output.txt &" means the script doesn't wait for
completion before moving on to the next one, the success message gets sent
back immediately. Here's the relevant part of Page 2:
for ($i = 0; $i <= $count; $i ++){
exec('python python_script.py > output.txt &');
}
// The following gets executed immediately, since the exec() calls in
the for-loop don't wait for the previous one to finish before being
carried out.
echo json_encode(array(
'success' => 'Success!'
));
What would be the best way to check to see if all the Python processes are
done before sending the success message back?
EDIT:
I came up with the following solution, to be inserted after the for-loop
containing the exec() calls. Any better ideas?
while not_empty(list_of_all_output.txt_files (one for each exec() call)):
foreach file in list_of_all_output.txt_files:
//check the last line of the file to see if a termination signal
has been written yet
if yes:
//remove file from list_of_all_output.txt_files
sleep(60)
No comments:
Post a Comment