I've got the following two files in my server
requests.php(controller) - receives incoming requests and executesprocess_query.phpin the background.process_query.php- contains a script which calls aCexecutable (usingshell_exec) to run against a certain number of files and writes some information to the database.
Right now as soon as the server receives a request in the controller, it immediately triggers the process_query.php script in the background. If there are too many incoming requests, it may result in server CPU outage. So I planned to have a max. limit to number of process_query.php processes that can run at a particular instant. For an example, let's assume the max. limit is 4 which implies only 4 instances of process_query.php can run at a time and others cannot start until one of the 4 processes finish.
I tried implementing this by having a table with request_id's and a flag to indicate process completion status. If there are 4 requests running right now then the table will have 4 entries with status flag as 0 in each.
When a new request arrives the process_query.php script runs into an infinite loop as shown in the code below and checks in the database for the total number of processes running at the moment. Since it is 4 as per our scenario, the script goes to sleep state (eg.10s). The loop keeps executing for every 10s until one of the process is completed. When the condition is met, the script comes out of the loop and performs the C call. After implementing this, I expected my activity monitor to show only 4 processes running. Unlikely there were n (total number of requests) processes running as the infinite loop kept the process_query.php process ticking. It made sense to me.
process_query.php
while(1) {
$req_count = execute("SELECT count(status) FROM `requests` WHERE status=0");
if($req_count == $max_request_limit) {
sleep(10);
continue;
}
break;
}
// ...code to execute the C script
// end of process_query.php
Which approach should I adapt in order to achieve this?