Repository navigation
Add blocking pipe read/write support - #306
Conversation
Implements support for pipe read and write operations in blocking mode (when no async runtime is available). Implementation uses a poll-first approach: - POSIX: Polls for readiness (POLLIN/POLLOUT) with infinite timeout, then performs the I/O operation using readv/writev - Windows: Directly performs I/O using ReadFile/WriteFile with NULL lpOverlapped, which blocks automatically This enables pipe I/O on stdin/stdout/stderr without requiring the async runtime, while safely handling shared file descriptors without modifying their blocking mode flags.
📝 WalkthroughWalkthroughThis PR adds blocking support for pipe read and write operations in the event handling module. It introduces platform-specific polling logic for POSIX systems before performing readv/writev operations, while Windows skips polling to preserve blocking behavior. Previously, these operations would panic; now they're fully handled via new helper functions. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@src/ev/blocking.zig`:
- Around line 140-162: The POSIX write path can raise SIGPIPE and terminate the
process before c.setError runs; update the blocking pipe write code so on
non-Windows platforms you ignore SIGPIPE (e.g., call signal(SIGPIPE, SIG_IGN)
via libc) before performing fs.writev in handlePipeWrite (or during module init
for the blocking API) to ensure writev returns EPIPE instead of killing the
process; keep the existing net.poll logic and still call c.setError on errors
from fs.writev (reference symbols: handlePipeWrite, PipeWrite, fs.writev,
net.poll, Completion, c.setError).
| fn handlePipeWrite(c: *Completion) void { | ||
| const data = c.cast(PipeWrite); | ||
|
|
||
| if (builtin.os.tag != .windows) { | ||
| // POSIX: poll first since pipes are non-blocking | ||
| var pfd = [_]net.pollfd{.{ | ||
| .fd = data.handle, | ||
| .events = net.POLL.OUT, | ||
| .revents = 0, | ||
| }}; | ||
| if (net.poll(&pfd, -1)) |_| {} else |err| { | ||
| c.setError(err); | ||
| return; | ||
| } | ||
| } | ||
|
|
||
| // Now write - Windows blocks, POSIX should be ready | ||
| if (fs.writev(data.handle, data.buffer.iovecs)) |bytes_written| { | ||
| c.setResult(.pipe_write, bytes_written); | ||
| } else |err| { | ||
| c.setError(err); | ||
| } | ||
| } |
There was a problem hiding this comment.
❓ Verification inconclusive
Script executed:
#!/bin/bash
# Search for SIGPIPE handling in the codebase
rg -i 'sigpipe' -C 3Repository: lalinsky/zio
Repository: lalinsky/zio
Exit code: 1
Script executed:
#!/bin/bash
# Search for signal handling more broadly
rg -i 'signal|sig\.' -C 2 | head -100Repository: lalinsky/zio
Repository: lalinsky/zio
Exit code: 0
stdout:
src/zio.zig-pub const Future = `@import`("sync/future.zig").Future;
src/zio.zig-
src/zio.zig:pub const Signal = `@import`("signal.zig").Signal;
src/zio.zig:pub const SignalKind = `@import`("signal.zig").SignalKind;
src/zio.zig-
src/zio.zig-pub const select = `@import`("select.zig").select;
--
src/select.zig-//
src/select.zig-// For queuing operations (Channel, Notify), when returning false the implementation
src/select.zig:// must transfer the wakeup to another waiter to avoid losing the signal/item.
src/select.zig-//
src/select.zig-// Guarantees:
--
src/select.zig- _ = self.winner.cmpxchgStrong(NO_WINNER, self.index, .acq_rel, .acquire);
src/select.zig-
src/select.zig: // Always signal parent - needed for both winner notification and
src/select.zig- // cleanup synchronization (waiting for in-flight wakes to complete)
src/select.zig: self.parent.signal();
src/select.zig- }
src/select.zig-};
--
src/select.zig- var winner: std.atomic.Value(usize) = .init(NO_WINNER);
src/select.zig-
src/select.zig: // Parent waiter that SelectWaiters will signal when they win
src/select.zig- var waiter = Waiter.init();
src/select.zig-
--
src/select.zig- const winner_index = winner.load(.acquire);
src/select.zig-
src/select.zig: // Count expected signals: all registered futures will signal unless we cancel them.
src/select.zig: // Successfully canceled futures (asyncCancelWait returns true) won't signal.
src/select.zig- var expected: u32 = `@intCast`(registered_count);
src/select.zig- inline for (fields, 0..) |field, i| {
--
src/select.zig-
src/select.zig- if (was_removed) {
src/select.zig: // Successfully removed from queue - won't signal
src/select.zig- expected -= 1;
src/select.zig- }
--
src/select.zig- }
src/select.zig-
src/select.zig: // Wait for all expected signals (winner + in-flight non-winners)
src/select.zig- waiter.wait(expected, .no_cancel);
src/select.zig- }
--
src/select.zig- }
src/select.zig-
src/select.zig: // Should never reach here - we were woken up, so something must be signaled
src/select.zig- unreachable;
src/select.zig-}
--
src/select.zig- const winner_index = winner.load(.acquire);
src/select.zig-
src/select.zig: // Count expected signals: all registered futures will signal unless we cancel them.
src/select.zig: // Successfully canceled futures (asyncCancelWait returns true) won't signal.
src/select.zig- var expected: u32 = `@intCast`(registered_count);
src/select.zig- for (awaitables[0..registered_count], 0..) |awaitable, i| {
--
src/select.zig- const was_removed = awaitable.asyncCancelWait(&select_waiters[i].wait_node);
src/select.zig- if (was_removed) {
src/select.zig: // Successfully removed from queue - won't signal
src/select.zig- expected -= 1;
src/select.zig- }
--
src/select.zig- }
src/select.zig-
src/select.zig: // Wait for all expected signals (winner + in-flight non-winners)
src/select.zig- waiter.wait(expected, .no_cancel);
src/select.zig- }
--
src/select.zig- checkSelfWait(task, future);
src/select.zig-
src/select.zig: // Winner tracking: for single future, winner is always 0 if signaled
src/select.zig- var winner: std.atomic.Value(usize) = .init(NO_WINNER);
src/select.zig- var waiter = Waiter.init();
--
src/select.zig-
src/select.zig- if (!was_removed) {
src/select.zig: // Wake is in-flight, wait for it to complete (1 signal expected)
src/select.zig- waiter.wait(1, .no_cancel);
src/select.zig- }
--
src/sync/channel.zig-/// proceed.
src/sync/channel.zig-///
src/sync/channel.zig:/// Channels can be closed to signal that no more values will be sent. After closing,
src/sync/channel.zig-/// receivers can drain any remaining buffered values before receiving `error.ChannelClosed`.
src/sync/channel.zig-///
--
src/sync/broadcast_channel.zig- ch.subscribe(consumer);
src/sync/broadcast_channel.zig- defer ch.unsubscribe(consumer);
src/sync/broadcast_channel.zig: _ = try b.wait(); // Signal that we're subscribed
src/sync/broadcast_channel.zig-
src/sync/broadcast_channel.zig- results[0] = try ch.receive(consumer);
--
src/sync/broadcast_channel.zig- ch.subscribe(consumer);
src/sync/broadcast_channel.zig- defer ch.unsubscribe(consumer);
src/sync/broadcast_channel.zig: _ = try b.wait(); // Signal that we're subscribed
src/sync/broadcast_channel.zig-
src/sync/broadcast_channel.zig- sum.* += try ch.receive(consumer);
Script executed:
#!/bin/bash
# Check the structure of blocking.zig and surrounding files to understand context
ls -la src/ev/
head -50 src/ev/blocking.zigRepository: lalinsky/zio
Repository: lalinsky/zio
Exit code: 0
stdout:
total 152
drwxr-xr-x 4 jailuser jailuser 300 Feb 8 22:10 .
drwxr-xr-x 8 jailuser jailuser 360 Feb 8 22:10 ..
-rw-r--r-- 1 jailuser jailuser 2038 Feb 8 22:10 README.md
-rw-r--r-- 1 jailuser jailuser 1456 Feb 8 22:10 backend.zig
drwxr-xr-x 2 jailuser jailuser 160 Feb 8 22:10 backends
-rw-r--r-- 1 jailuser jailuser 5901 Feb 8 22:10 blocking.zig
-rw-r--r-- 1 jailuser jailuser 1101 Feb 8 22:10 buf.zig
-rw-r--r-- 1 jailuser jailuser 56977 Feb 8 22:10 completion.zig
-rw-r--r-- 1 jailuser jailuser 12770 Feb 8 22:10 heap.zig
-rw-r--r-- 1 jailuser jailuser 30583 Feb 8 22:10 loop.zig
-rw-r--r-- 1 jailuser jailuser 6753 Feb 8 22:10 queue.zig
-rw-r--r-- 1 jailuser jailuser 3666 Feb 8 22:10 root.zig
drwxr-xr-x 2 jailuser jailuser 220 Feb 8 22:10 test
-rw-r--r-- 1 jailuser jailuser 8173 Feb 8 22:10 tests.zig
-rw-r--r-- 1 jailuser jailuser 7600 Feb 8 22:10 thread_pool.zig
// SPDX-FileCopyrightText: 2025 Lukáš Lalinský
// SPDX-License-Identifier: MIT
//! Blocking execution of I/O operations without event loop.
//!
//! This module provides synchronous execution of file and pipe operations
//! for use in non-async contexts (when there's no runtime/executor).
const std = `@import`("std");
const builtin = `@import`("builtin");
const Completion = `@import`("completion.zig").Completion;
const PipeClose = `@import`("completion.zig").PipeClose;
const PipeRead = `@import`("completion.zig").PipeRead;
const PipeWrite = `@import`("completion.zig").PipeWrite;
const common = `@import`("backends/common.zig");
const fs = `@import`("../os/fs.zig");
const net = `@import`("../os/net.zig");
/// Execute a completion synchronously without an event loop.
/// This is used when there's no async runtime available.
///
/// Supports file and pipe operations (read/write use poll+I/O on POSIX).
/// Network operations and timers are not supported.
pub fn executeBlocking(c: *Completion, allocator: std.mem.Allocator) void {
// Mark completion as having no loop
c.loop = null;
switch (c.op) {
.file_open => common.handleFileOpen(c, allocator),
.file_create => common.handleFileCreate(c, allocator),
.file_close => common.handleFileClose(c),
.file_read => common.handleFileRead(c),
.file_write => common.handleFileWrite(c),
.file_sync => common.handleFileSync(c),
.file_set_size => common.handleFileSetSize(c),
.file_set_permissions => common.handleFileSetPermissions(c),
.file_set_owner => common.handleFileSetOwner(c),
.file_set_timestamps => common.handleFileSetTimestamps(c),
.dir_create_dir => common.handleDirCreateDir(c, allocator),
.dir_rename => common.handleDirRename(c, allocator),
.dir_delete_file => common.handleDirDeleteFile(c, allocator),
.dir_delete_dir => common.handleDirDeleteDir(c, allocator),
.file_size => common.handleFileSize(c),
.file_stat => common.handleFileStat(c, allocator),
.dir_open => common.handleDirOpen(c, allocator),
.dir_close => common.handleDirClose(c),
.dir_set_permissions => common.handleDirSetPermissions(c),
.dir_set_owner => common.handleDirSetOwner(c),
.dir_set_file_permissions => common.handleDirSetFilePermissions(c, allocator),
.dir_set_file_owner => common.handleDirSetFileOwner(c, allocator),
Pipe write works, but SIGPIPE can silently kill the process in the no-runtime case.
The poll-then-write logic is correct. The issue: if the read end of the pipe closes before you write (like myapp | head where head exits), writev triggers SIGPIPE and the process dies—the error handling never runs.
Since this module is explicitly for use without a runtime, there's no signal handler installed by default. Standard runtimes ignore SIGPIPE at startup; your blocking API users won't get that. Either document that callers must handle SIGPIPE themselves (e.g., signal(SIGPIPE, SIG_IGN) before calling blocking operations on pipes), or install a handler in the blocking path.
🤖 Prompt for AI Agents
In `@src/ev/blocking.zig` around lines 140 - 162, The POSIX write path can raise
SIGPIPE and terminate the process before c.setError runs; update the blocking
pipe write code so on non-Windows platforms you ignore SIGPIPE (e.g., call
signal(SIGPIPE, SIG_IGN) via libc) before performing fs.writev in
handlePipeWrite (or during module init for the blocking API) to ensure writev
returns EPIPE instead of killing the process; keep the existing net.poll logic
and still call c.setError on errors from fs.writev (reference symbols:
handlePipeWrite, PipeWrite, fs.writev, net.poll, Completion, c.setError).
There was a problem hiding this comment.
SIGPIPE is already handled by Zig itself
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
Zig SIGPIPE handling default behavior
💡 Result:
On POSIX/Unix targets, Zig’s default for executables is to disable SIGPIPE by installing a no-op SIGPIPE handler (not SIG_IGN). This prevents the process from being terminated when writing to a closed pipe/socket; instead the write fails with EPIPE (surfacing in Zig as error.BrokenPipe). Zig uses a no-op handler specifically so the disposition won’t be inherited across exec the way SIG_IGN would be. [1][2]
To restore normal SIGPIPE behavior (default disposition / process can be killed by SIGPIPE), set:
const std = `@import`("std");
pub const std_options: std.Options = .{
.keep_sigpipe = true,
};[1] https://ziglang.org/download/0.12.0/release-notes.html
[2] https://fossies.org/linux/zig/lib/std/std.zig
@lalinsky You're absolutely right, and I apologize for the incorrect review comment. Zig installs a no-op SIGPIPE handler by default on POSIX systems, which prevents process termination and causes writes to closed pipes to return EPIPE (surfaced as error.BrokenPipe) instead. Your blocking pipe write implementation is safe—fs.writev will return the error properly and c.setError will be called as expected.
Thank you for the correction!
🧠 Learnings used
Learnt from: lalinsky
Repo: lalinsky/zio PR: 41
File: src/udp.zig:79-82
Timestamp: 2025-10-10T05:59:17.087Z
Learning: In UDP socket operations (src/udp.zig), error.Canceled from result_data.result represents OS/IO-level cancellation (e.g., io_uring), not user-requested cancellation. User cancellation is handled by waitForXevCompletion() via try. OS-level error.Canceled should be mapped to error.Unexpected as it represents an unexpected system event.
Learnt from: lalinsky
Repo: lalinsky/zio PR: 179
File: src/os/windows.zig:424-424
Timestamp: 2026-01-07T13:15:48.677Z
Learning: In `src/os/windows.zig`, WSABUF must be re-exported from `std.os.windows.ws2_32.WSABUF` rather than defined locally because it needs to satisfy `std.Io.Reader` compatibility requirements.
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/stdio.zig:117-129
Timestamp: 2026-01-10T14:08:47.638Z
Learning: In src/stdio.zig, swapCancelProtectionImpl's return value is an opaque restoration token, not a reflection of actual shield state. The std.Io contract guarantees paired calls (old = swap(new); defer swap(old)), allowing the implementation to use increment/decrement logic (swap(.blocked) increments shield_count and returns .unblocked; swap(.unblocked) decrements and returns .blocked) without exposing internal state.
Learnt from: lalinsky
Repo: lalinsky/zio PR: 236
File: src/net.zig:1066-1072
Timestamp: 2026-01-25T12:07:40.168Z
Learning: In `src/net.zig`, the `readVec` and `writeVec` methods intentionally truncate buffers beyond `max_vecs` (16 buffers) without error. This silent truncation is by design.
Implements support for pipe read and write operations in blocking mode (when no async runtime is available). Implementation uses a poll-first approach: - POSIX: Polls for readiness (POLLIN/POLLOUT) with infinite timeout, then performs the I/O operation using readv/writev - Windows: Directly performs I/O using ReadFile/WriteFile with NULL lpOverlapped, which blocks automatically This enables pipe I/O on stdin/stdout/stderr without requiring the async runtime, while safely handling shared file descriptors without modifying their blocking mode flags.
Summary
Implementation Details
POSIX:
POLLIN/POLLOUTusing infinite timeout to wait for readinessreadv/writevwhich should succeed immediatelyWindows:
ReadFile/WriteFilewith NULL lpOverlappedBenefits
Testing
Tested by running hello-world example without runtime initialization - successfully writes to stdout in blocking mode.
Fixes #287