stream_select
stream_select(?array &$read, ?array &$write, ?array &$except, ?int $seconds, ?int $microseconds = null, ?resource $context = null): int|false
I/O multiplexing — the direct descendant of C select(2): watches the read/write/except stream sets until any become ready or the timeout expires; returns the number of ready streams (0 = timeout, false = error, so test with === false), and rewrites the three arrays in place into the ready subset.
C C23
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
int main(void) {
int fds[2];
pipe(fds); // fds[0] = read end, fds[1] = write end (POSIX)
/* select(2): three fd sets plus a timeout — PHP's direct ancestor. */
fd_set rfds;
struct timeval tv;
FD_ZERO(&rfds);
FD_SET(fds[0], &rfds);
tv.tv_sec = 0;
tv.tv_usec = 50000;
int n = select(fds[0] + 1, &rfds, NULL, NULL, &tv); // empty pipe: timeout
printf("empty-pipe: %d\n", n);
write(fds[1], "ping", 4);
FD_ZERO(&rfds);
FD_SET(fds[0], &rfds);
tv.tv_sec = 1;
tv.tv_usec = 0;
n = select(fds[0] + 1, &rfds, NULL, NULL, &tv); // pending data: readable
printf("data-ready: %d\n", n);
char buf[8] = {0};
read(fds[0], buf, 4);
printf("%s\n", buf);
return 0;
}
empty-pipe: 0 data-ready: 1 ping
C++ C++26
#include <iostream>
#include <unistd.h>
#include <sys/select.h>
int main() {
int fds[2];
pipe(fds); // fds[0] = read end, fds[1] = write end (POSIX)
// C++ uses the same POSIX select(2); production code would
// reach for epoll/kqueue or Boost.Asio instead.
fd_set rfds;
timeval tv;
FD_ZERO(&rfds);
FD_SET(fds[0], &rfds);
tv.tv_sec = 0;
tv.tv_usec = 50000;
int n = select(fds[0] + 1, &rfds, nullptr, nullptr, &tv); // empty pipe
std::cout << "empty-pipe: " << n << '\n';
write(fds[1], "ping", 4);
FD_ZERO(&rfds);
FD_SET(fds[0], &rfds);
tv.tv_sec = 1;
tv.tv_usec = 0;
n = select(fds[0] + 1, &rfds, nullptr, nullptr, &tv); // pending data
std::cout << "data-ready: " << n << '\n';
char buf[8] = {0};
read(fds[0], buf, 4);
std::cout << buf << '\n';
return 0;
}
empty-pipe: 0 data-ready: 1 ping
C# v11.0.100
using System.Net;
using System.Net.Sockets;
using System.Text;
// Socket.Select is the scarce standard-library multiplexor in .NET
// (sockets only; a loopback pair stands in for a pipe).
var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect((IPEndPoint)listener.LocalEndPoint!);
var server = listener.Accept();
listener.Close();
var write = new List<Socket>();
var error = new List<Socket>();
// empty pipe: Select times out and drains the read list
var read = new List<Socket> { server };
Socket.Select(read, write, error, 50_000);
Console.WriteLine($"empty-pipe: {read.Count}");
client.Send(Encoding.ASCII.GetBytes("ping"));
read = new List<Socket> { server };
Socket.Select(read, write, error, 1_000_000);
Console.WriteLine($"data-ready: {read.Count}");
var buf = new byte[8];
int len = server.Receive(buf);
Console.WriteLine(Encoding.ASCII.GetString(buf, 0, len));
empty-pipe: 0 data-ready: 1 ping
Go v1.27.4
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan string, 1)
// Go's select multiplexes CHANNELS, not fds — with no value
// ready the timeout branch wins.
select {
case v := <-ch:
fmt.Println("data-ready:", v)
case <-time.After(50 * time.Millisecond):
fmt.Println("empty-pipe: 0")
}
// once a value is pending, its case fires immediately
ch <- "ping"
select {
case v := <-ch:
fmt.Println("data-ready:", v)
case <-time.After(time.Second):
fmt.Println("empty-pipe: 0")
}
}
empty-pipe: 0 data-ready: ping
Java v27.0.1
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
public class Main {
public static void main(String[] args) throws Exception {
// Java NIO: a Selector multiplexes channels by interest set
// (OP_READ/OP_WRITE); a Pipe is an in-process pair, no network.
Pipe pipe = Pipe.open();
Selector selector = Selector.open();
pipe.source().configureBlocking(false);
pipe.source().register(selector, SelectionKey.OP_READ);
// empty pipe: select(timeout) returns the ready-key count
int n = selector.select(200);
System.out.println("empty-pipe: " + n);
pipe.sink().write(ByteBuffer.wrap("ping".getBytes()));
n = selector.select(1000);
System.out.println("data-ready: " + n);
ByteBuffer buf = ByteBuffer.allocate(8);
pipe.source().read(buf);
System.out.println(new String(buf.array(), 0, buf.position()));
}
}
empty-pipe: 0 data-ready: 1 ping
JavaScript v26.13.1
const net = require('node:net');
// JS has no select: the event loop multiplexes every connection
// for you; readiness arrives as events, not return values.
const server = net.createServer((conn) => {
conn.on('data', (chunk) => {
console.log('data-ready: 1');
console.log(chunk.toString().trim());
conn.end();
server.close();
});
});
server.listen(0, '127.0.0.1', () => {
const port = server.address().port;
const client = net.createConnection(port, '127.0.0.1', () => {
// no data pending: the loop simply idles instead of "timing out"
console.log('empty-pipe: 0');
setTimeout(() => client.write('ping\n'), 20);
});
});
empty-pipe: 0 data-ready: 1 ping
PHP v8.6.0
[$reader, $writer] = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
stream_set_blocking($reader, false);
$w = null;
$e = null;
$read = [$reader];
$n = stream_select($read, $w, $e, 0, 50000); // empty pipe: times out
echo "empty-pipe: $n\n";
fwrite($writer, 'ping');
$read = [$reader];
$n = stream_select($read, $w, $e, 1); // pending data: readable at once
echo "data-ready: $n\n";
echo fread($reader, 4), "\n";
empty-pipe: 0 data-ready: 1 ping
Python v3.15.2
import selectors
import socket
# selectors.DefaultSelector picks epoll/kqueue/select automatically.
sel = selectors.DefaultSelector()
reader, writer = socket.socketpair()
reader.setblocking(False)
sel.register(reader, selectors.EVENT_READ)
# empty pipe: select() times out and returns no ready events
n = len(sel.select(timeout=0.2))
print(f"empty-pipe: {n}")
writer.sendall(b"ping")
n = len(sel.select(timeout=1))
print(f"data-ready: {n}")
print(reader.recv(4).decode())
empty-pipe: 0 data-ready: 1 ping
Rust v1.99.1
use mio::net::{TcpListener, TcpStream};
use mio::{Events, Interest, Poll, Token};
use std::io::{Read, Write};
use std::time::Duration;
const SERVER: Token = Token(0);
const CLIENT: Token = Token(1);
const ACCEPTED: Token = Token(2);
fn main() {
// mio is Rust's minimal multiplexor: sockets registered with a
// Poll, readiness delivered as token-tagged events.
let mut poll = Poll::new().unwrap();
let mut events = Events::with_capacity(8);
let mut listener = TcpListener::bind("127.0.0.1:0".parse().unwrap()).unwrap();
let local = listener.local_addr().unwrap();
let mut client = TcpStream::connect(local).unwrap();
poll.registry().register(&mut listener, SERVER, Interest::READABLE).unwrap();
poll.registry().register(&mut client, CLIENT, Interest::WRITABLE).unwrap();
// drive the non-blocking connect, then accept the loopback pair
let mut server = None;
while server.is_none() {
poll.poll(&mut events, Some(Duration::from_secs(1))).unwrap();
for ev in events.iter() {
if ev.token() == SERVER && ev.is_readable() {
server = Some(listener.accept().unwrap().0);
}
}
}
let mut server = server.unwrap();
poll.registry().register(&mut server, ACCEPTED, Interest::READABLE).unwrap();
// empty pipe: one timed poll, counting only ACCEPTED-readable events
events.clear();
poll.poll(&mut events, Some(Duration::from_millis(200))).unwrap();
let ready = events.iter().filter(|e| e.token() == ACCEPTED && e.is_readable()).count();
println!("empty-pipe: {}", ready);
client.write_all(b"ping").unwrap();
let mut ready = 0usize;
while ready == 0 {
events.clear();
poll.poll(&mut events, Some(Duration::from_secs(1))).unwrap();
ready += events.iter().filter(|e| e.token() == ACCEPTED && e.is_readable()).count();
}
println!("data-ready: 1");
let mut buf = [0u8; 8];
let len = server.read(&mut buf).unwrap();
println!("{}", std::str::from_utf8(&buf[..len]).unwrap());
}
empty-pipe: 0 data-ready: 1 ping
TypeScript v26.13.1
import * as net from 'node:net';
// TS has no select either: the event loop multiplexes every
// connection; readiness arrives as events, not return values.
const server = net.createServer((conn: net.Socket) => {
conn.on('data', (chunk: Buffer) => {
console.log('data-ready: 1');
console.log(chunk.toString().trim());
conn.end();
server.close();
});
});
server.listen(0, '127.0.0.1', () => {
const port = (server.address() as net.AddressInfo).port;
const client = net.createConnection(port, '127.0.0.1', () => {
// no data pending: the loop simply idles instead of "timing out"
console.log('empty-pipe: 0');
setTimeout(() => client.write('ping\n'), 20);
});
});
empty-pipe: 0 data-ready: 1 ping
Language differences
PHP: stream_select is the direct descendant of C select(2) — it watches the read/write/except stream sets until any become ready or the timeout (seconds + microseconds) expires; it returns the number of READY streams, 0 on timeout and false on error — test with === false (the 0==false trap, manual Note); afterwards the three arrays are rewritten in place into the ready subset (keys preserved).
Key semantics: a stream at EOF also counts as "readable" (fread returns an empty string immediately, manual read-parameter note); a stream whose PHP-side internal buffer already holds data is reported ready without any OS select() call (manual Note); select is designed for non-blocking streams — mixing it with blocking streams is the classic mistake (manual user note).
Versions: the optional $context parameter was added in 8.6.0 (its error-handling options govern how errors of this call are reported); microseconds may be null since 8.1 (second-only timeout); seconds = null blocks indefinitely.
C: the same family as select(2) — three fd_sets plus a timeval; a pipe(2) self-pair is the minimal demo; mind the FD_SETSIZE cap (1024) and reset the sets before every call.
C++: same as C (the POSIX API is available verbatim); production code uses epoll/kqueue or Boost.Asio.
C#: Socket.Select is the scarce standard-library multiplexor — on timeout it drains all lists (the read list's count is the ready count); sockets only, so a 127.0.0.1 loopback pair stands in for a pipe.
Go: beware, different concept — Go's select keyword multiplexes over channels (a choice among communications); the runtime's netpoller (epoll/kqueue) already does the fd-level multiplexing for you, so application code rarely touches fd sets.
Java: NIO Selector — channels register by interest set (OP_READ/OP_WRITE) and select(timeout) returns the ready-key count; the example uses a Pipe (in-process, no network).
Python: the selectors module — DefaultSelector auto-picks epoll/kqueue; register(fd, EVENT_READ) + select(timeout) returns a list of ready (key, mask) pairs.
JS/TS: no select — the event loop multiplexes natively: registering a callback (on('data')) IS the "watch", and readiness arrives as events; the example reproduces the empty-pipe/data-ready two-state assertion in event semantics over a loopback TCP pair.
Rust: no multiplexing in std — production uses mio/polling/tokio; the example uses mio: a loopback TCP pair registered with Poll, asserting the timed-poll and ready-poll states.