master
 1const std = @import("std");
 2const Io = std.Io;
 3
 4// 42 is expected by parent; other values result in test failure
 5var exit_code: u8 = 42;
 6
 7pub fn main() !void {
 8    var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator);
 9    const arena = arena_state.allocator();
10
11    var threaded: std.Io.Threaded = .init(arena);
12    defer threaded.deinit();
13    const io = threaded.io();
14
15    try run(arena, io);
16    arena_state.deinit();
17    std.process.exit(exit_code);
18}
19
20fn run(allocator: std.mem.Allocator, io: Io) !void {
21    var args = try std.process.argsWithAllocator(allocator);
22    defer args.deinit();
23    _ = args.next() orelse unreachable; // skip binary name
24
25    // test cmd args
26    const hello_arg = "hello arg";
27    const a1 = args.next() orelse unreachable;
28    if (!std.mem.eql(u8, a1, hello_arg)) {
29        testError("first arg: '{s}'; want '{s}'", .{ a1, hello_arg });
30    }
31    if (args.next()) |a2| {
32        testError("expected only one arg; got more: {s}", .{a2});
33    }
34
35    // test stdout pipe; parent verifies
36    try std.fs.File.stdout().writeAll("hello from stdout");
37
38    // test stdin pipe from parent
39    const hello_stdin = "hello from stdin";
40    var buf: [hello_stdin.len]u8 = undefined;
41    const stdin: std.fs.File = .stdin();
42    var reader = stdin.reader(io, &.{});
43    const n = try reader.interface.readSliceShort(&buf);
44    if (!std.mem.eql(u8, buf[0..n], hello_stdin)) {
45        testError("stdin: '{s}'; want '{s}'", .{ buf[0..n], hello_stdin });
46    }
47}
48
49fn testError(comptime fmt: []const u8, args: anytype) void {
50    var stderr_writer = std.fs.File.stderr().writer(&.{});
51    const stderr = &stderr_writer.interface;
52    stderr.print("CHILD TEST ERROR: ", .{}) catch {};
53    stderr.print(fmt, args) catch {};
54    if (fmt[fmt.len - 1] != '\n') {
55        stderr.writeByte('\n') catch {};
56    }
57    exit_code = 1;
58}