forkpty.zig

· erock's pastes · raw

expires: 2025-09-25

 1const std = @import("std");
 2const os = std.os;
 3const io = std.io;
 4// This imports the separate module containing `root.zig`. Take a look in `build.zig` for details.
 5const lib = @import("zesh_lib");
 6
 7const c = @cImport({
 8    @cInclude("pty.h");
 9});
10
11pub fn main() !void {
12    const args = os.argv;
13    for (args) |arg| {
14        const a: []const u8 = std.mem.span(arg);
15        std.log.debug("args {s}", .{a});
16    }
17    // const cmd: []const u8 = std.mem.span(args[1]);
18    // if (std.mem.eql(u8, cmd, "client")) {
19    //     try run_client();
20    // } else if (std.mem.eql(u8, cmd, "server")) {
21    //     try run_server();
22    // } else {
23    //     return error.InvalidArg;
24    // }
25
26    const master_fd: [*c]c_int = 0;
27    var pid: c.pid_t = 0;
28    pid = c.forkpty(master_fd, null, null, null);
29    if (pid == -1) {
30        std.debug.print("forkpty failed\n", .{});
31        return;
32    }
33
34    if (pid == 0) {
35        const ag = [_:null]?[*:0]const u8{"/usr/bin/fish"};
36        // child process
37        std.debug.print("This is the child process with PID: {}\n", .{os.linux.getpid()});
38        const err = std.posix.execvpeZ(ag[0].?, &ag, std.c.environ);
39        std.log.err("exec failed: {}", .{err});
40    } else {
41        // parent process
42        var status: u32 = 0;
43        std.debug.print("This is the parent process with PID: {} and child PID: {}\n", .{ os.linux.getpid(), pid });
44        const wait_result = os.linux.waitpid(pid, &status, 0);
45        if (wait_result != 0) {
46            std.debug.print("Command returned {}.\n", .{wait_result});
47        }
48    }
49}
50
51// fn run_server() !void {
52//     std.log.debug("server is running", .{});
53// }
54// 
55// fn run_client() !void {
56//     std.log.debug("client is running", .{});
57// }