From 6f1c762e789cd746e20cd7597aab0316d2c2fcd9 Mon Sep 17 00:00:00 2001 From: Lucas Faria Mendes Date: Fri, 5 Dec 2025 03:31:01 -0300 Subject: codecrafters submit [skip ci] --- src/executor.zig | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) (limited to 'src/executor.zig') diff --git a/src/executor.zig b/src/executor.zig index 839fcda..a53ade8 100644 --- a/src/executor.zig +++ b/src/executor.zig @@ -27,3 +27,42 @@ pub fn runExternalProgram(allocator: std.mem.Allocator, program_path: []const u8 _ = std.posix.waitpid(pid, 0); } } + +pub fn runExternalProgramWithRedirect(allocator: std.mem.Allocator, program_path: []const u8, argv: []const []const u8, output_file: []const u8) !void { + const argv_z = try allocator.allocSentinel(?[*:0]const u8, argv.len, null); + defer allocator.free(argv_z); + + for (argv, 0..) |arg, i| { + argv_z[i] = (try allocator.dupeZ(u8, arg)).ptr; + } + defer { + for (argv_z[0..argv.len]) |arg_ptr| { + if (arg_ptr) |ptr| allocator.free(std.mem.span(ptr)); + } + } + + const program_path_z = try allocator.dupeZ(u8, program_path); + defer allocator.free(program_path_z); + + const output_file_z = try allocator.dupeZ(u8, output_file); + defer allocator.free(output_file_z); + + const pid = try std.posix.fork(); + + if (pid == 0) { + const cwd = std.fs.cwd(); + const fd = cwd.createFile(output_file, .{}) catch { + std.posix.exit(1); + }; + defer fd.close(); + + try std.posix.dup2(fd.handle, 1); + + _ = std.posix.execveZ(program_path_z, argv_z, std.c.environ) catch { + std.posix.exit(1); + }; + unreachable; + } else { + _ = std.posix.waitpid(pid, 0); + } +} -- cgit v1.2.3