I'm running ScriptA and ScriptB, A executes B. B echos
messages after it finishes each of its functions. Thing is: B's functions may get stuck because they request data to a slow server with short session expiring so I'm trying to kill B after certain time has passed since the last echoed message. Here is an example:
ScriptB:
echo "string1\n";
sleep(1);
echo "string2\n";
sleep(1);
echo "string3\n";
sleep(1);
echo "string4\n";
sleep(3);
echo "string5\n";
ScriptA
$cmd = "php ScriptB";
$timeout_tolerance = 2; //
$last_response = time(); // start time
ob_implicit_flush(true);
ob_end_flush();
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a pipe that the child will write to
);
flush();
$process = proc_open($cmd, $descriptorspec, $pipes, null, array());
echo "here is 1\n";
if (is_resource($process)) {
while ($s = fgets($pipes[1])) {
print $s;
$m = $s;
$last_response = time();
while ($s === $m) {
echo "here is 2\n";
$m = fgets($pipes[1]);
if((time() - $last_response) > $timeout_tolerance){
echo "here is 3\n";
break;
}
echo "here is 4\n";
sleep(2);
}
}
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
echo "here is 5\n";
}
When I run Script A this is what I get as an output:
here is 1
string1
here is 2
here is 4
string3
here is 2
here is 4
string5
here is 2
here is 4
here is 5
As you may see; string2
nor string4
are outputted and scriptB should be killed before string5
is echoed. I know this is an error on my code, thing is I have never used functions such as fgets()
and I'm having a hard time understanding them.