Skip to content

std.ChildProcess can deadlock if both stdout and stderr are long and interleaved #6343

Closed

Description

@andrewrk

Related: #938 but this needs to work with blocking I/O too.

// TODO need to poll to read these streams to prevent a deadlock (or rely on evented I/O).
const stdout = try stdout_in.readAllAlloc(args.allocator, args.max_output_bytes);
errdefer args.allocator.free(stdout);
const stderr = try stderr_in.readAllAlloc(args.allocator, args.max_output_bytes);
errdefer args.allocator.free(stderr);

This is a flaw in the API design because this example code above will be duplicated many times in users of this API. We need to eliminate this footgun.

Activity

  1. added
    bug
    breaking
    standard library
    on Sep 14, 2020
  2. added this to the 0.8.0 milestone on Sep 14, 2020
  3. LemonBoy commented on Oct 19, 2020

    @LemonBoy
    Contributor

    A simple test case to show the deadlock on Linux:

    const std = @import("std");
    
    pub fn main() !void {
         const allocator = std.heap.page_allocator;
    
         const args = try std.process.argsAlloc(allocator);
    
         if (args.len != 1) {
             // Enough to saturate the pipe buffer
             try std.io.getStdErr().writeAll("A" ** 65536);
             try std.io.getStdErr().writeAll("A" ** 65536);
             return;
         }
    
         const child = try std.ChildProcess.exec(.{
             .allocator = allocator,
             // Re-exec this program and fill the stderr pipe
             .argv = &[_][]const u8{ "foo", "-nonexistentflag" },
             .max_output_bytes = 1_000_000,
         });
    
         std.debug.print("O {}", .{child.stdout});
         std.debug.print("E {}", .{child.stderr});
    }

    From my POV the API is great as-is, if the user asks for stdout/stderr to be a pipe they must be ready to handle both streams at the same time using async IO/threads or whatever they prefer. The problem here is that some consumers, such as the ones in the Zig codebase marked with todo, only need a way to execute some command and read all the output.
    To accommodate such uses of ChildProcess I'd propose to:

    • Add the polling logic in exec. This is the blessed function that abstracts the complexity away from the user, reading stdin/stdout by hand is still allowed but you're on your own.
    • Add a way to combine the stdin and stdout into a single stream, as many times you just need the complete subprocess output.

    Making the polling work on Windows is, as always, a bit challenging as select() doesn't work for pipes and neither do many other parts of the async IO API. A quick search shows that pretty much everyone is "emulating" select by polling (PeekNamedPipe) and sleeping... Not the most elegant solution but it seems to work.

  4. prime31 commented on Nov 21, 2020

    @prime31
    Contributor

    I just ran into the deadlock on macos with a process that dumps a lot of data to stderr.

  5. LemonBoy commented on Nov 21, 2020

    @LemonBoy
    Contributor

    Does #6750 work for you?

  6. andrewrk commented on Dec 29, 2020

    @andrewrk
    MemberAuthor

    I did a partial merge of @LemonBoy's #6750 which solves the problem for the exec use case. The partial merge solves the issue for POSIX but not Windows. I'm closing the PR because it's an old draft, but this comment is a reminder that there is working(?) tested(?) code for Windows sitting around that could be utilized to solve this use case.

  7. modified the milestones: 0.8.0, 0.8.1 on Jun 4, 2021
  8. marler8997 commented on Jun 17, 2021

    @marler8997
    Contributor

    I ran into this today. I put together this program to reproduce on Windows:

    const std = @import("std");
    
    pub fn main() !void {
        const args = (try std.process.argsAlloc(std.heap.page_allocator))[1..];
        if (args.len == 0) {
            const self_exe_path = try std.fs.selfExePathAlloc(std.heap.page_allocator);
            std.log.info("executing child process '{s}'", .{self_exe_path});
            const result = try std.ChildProcess.exec(.{
                .allocator = std.heap.page_allocator,
                .argv = &[_][]const u8 { self_exe_path, "child"},
            });
            std.log.info("child process done", .{});
        } else {
            // just print a bunch to stderr to hit deadlock
            while (i < 100) : (i += 1) {
                try std.io.getStdErr().writer().print("{}: -----------------------------------------------------------------------------\n", .{i});
            }
        }
    }
  9. LemonBoy commented on Jun 17, 2021

    @LemonBoy
    Contributor

    Try applying the windows code path contained in #6750.

  10. marler8997 commented on Jun 17, 2021

    @marler8997
    Contributor

    @LemonBoy, tested and it fixes the issue :)

  11. modified the milestones: 0.8.1, 0.9.1 on Aug 31, 2021
  12. andrewrk commented on Sep 16, 2021

    @andrewrk
    MemberAuthor

    Fixed by @marler8997 and the fix landed in 0.8.1.

  13. modified the milestones: 0.9.1, 0.8.1 on Sep 16, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    breakingbugstandard library

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions