Skip to content

Commit

Permalink
Fix #309 - Use stream_select instead of non-blocking STDIN
Browse files Browse the repository at this point in the history
The idiom used in the readStdin function from src/Utils/CLI.php is not
entirely error-prone: marking stdin as non-blocking and then reading
from it can lead to racy scenarios where we are not able to catch
what's being fed to the program.  This can be seen very frequently on
s390x, where a loop like this:

  $ while echo "invalid query" | /usr/bin/php7.4 /path/to//highlight-query; do sleep 1; done;

will lead to failures once on every few runs (as can be seen in the
description of issue #309).

This commit implements the more robust method which uses stream_select
to wait for stdin to become available, but resorts to a sensible
timeout value (0.2 seconds) which will prevent the blocking from
happening.

I tested this patch extensively on s390x and amd64, and noticed that
the non-determinism is gone.

Signed-off-by: Sergio Durigan Junior <[email protected]>
  • Loading branch information
sergiodj authored and williamdes committed Aug 27, 2020
1 parent 6f31612 commit 5419487
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions src/Utils/CLI.php
Original file line number Diff line number Diff line change
Expand Up @@ -233,11 +233,22 @@ public function runTokenize()
return 1;
}

public function readStdin() {
stream_set_blocking(STDIN, false);
$stdin = stream_get_contents(STDIN);
// restore-default block-mode setting
stream_set_blocking(STDIN, true);
public function readStdin()
{
$read = [STDIN];
$write = [];
$except = [];

// Assume there's nothing to be read from STDIN.
$stdin = null;

// Try to read from STDIN. Wait 0.2 second before timing out.
$result = stream_select($read, $write, $except, 0, 2000);

if ($result > 0) {
$stdin = stream_get_contents(STDIN);
}

return $stdin;
}
}

0 comments on commit 5419487

Please sign in to comment.