问题
I have a PHP script that run on console.
while(1) {
doStuff();
sleep(2);
}
I need to accept input from the console. I don't want loop stop each time and wait for me to input some text.
What i want is while loop continue as normal, if i type something in console, php script able to read that text and update some variable.
Can this be done ?
回答1:
You can do this with non-blocking I/O. You'll need the stream_set_blocking method and stream_select:
stream_set_blocking(STDIN, FALSE);
while (1) {
doStuff();
$readStreams = [STDIN];
$timeout = 2;
// stream_select will block for $timeout seconds OR until STDIN
// contains some data to read.
$numberOfStreamsWithData = stream_select(
$readStreams,
$writeStreams = [],
$except = [],
$timeout
);
if ($numberOfStreamsWithData > 0) {
$userInput = fgets(STDIN);
// process $userInput as you see fit
} else {
// no user input; repeat loop as normal
}
}
来源:https://stackoverflow.com/questions/34819448/php-loop-listen-for-user-input