summaryrefslogtreecommitdiff
path: root/src/main.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-10-29 10:48:56 -0300
committerGabriel Schneider <[email protected]>2026-10-29 12:01:27 -0300
commit4ffe5c93b3087f245f5b57a822ab0ecf41cc085c (patch)
treeede4d5de12fe169838f1f5993a9896bd32f45715 /src/main.zig
parentcb2a6cd79e443d671f5255d262ea79b7e26552a5 (diff)
downloadpardes-4ffe5c93b3087f245f5b57a822ab0ecf41cc085c.tar.gz
pardes-4ffe5c93b3087f245f5b57a822ab0ecf41cc085c.zip
sessions register with the daemon: a terminal's session forked off its stub, Detach and --attach in place for terminals and windows, pty masters kept, Adopt
pardes in a terminal reaches (or starts) the daemon, opens /dev/tty and forks: the child is the session, in a session of its own (setsid), drawing on that terminal (tty.Term.fd, a raw vaxis Tty made from the fd); the parent stays as its stub, the job the shell waits on. Not the daemon spawning it from a passed fd, env and argv: the user's terminals each run in a 9ns user and mount namespace, which a session spawned by a per-user daemon would not share, and a fork costs one small process's page tables where the spawn cost an IPC and an exec. GUI windows and --detach sessions just register. tty: Detach (and a terminal's end: EOF, EIO, a hangup the stub passes on, taken on the signal thread) puts the terminal back, drops it and the stub's stdio, tells the stub (which ends, exit 0), and leaves the session running with nothing drawn (Host.watched), its messages on the clock and `size` its own. pardes --attach[=name] hands its terminal through the daemon; the session enters it as the first one, sized, queried and drawn whole, and that process is its stub until it leaves. A hangup never ends a kept session; TERM and INT do, telling the daemon so the shells go with it (one async-signal-safe send). gui: Detach closes the window (its swapchain or renderer) and keeps the device, atlas and pipelines; the loop sleeps on SDL's queue; pardes-gui --attach[=name] opens a window again. Closing a window still quits. --detach is a session started detached: the tty host with no terminal yet, the GUI with a hidden window closed at once. forkShell sends the daemon a dup of every master and the hosts tell it what they close, so a session killed outright leaves its shells running; the new Adopt word takes them in as terminal panes (the Tty word's pane, its spawn taking the pty, a 1x1 size then the pane's to make it redraw). The Attach word, which switched a session's own terminal to a detached session through the frames, goes, with its effect and request in the core. PARDES_DAEMON=off (the e2e harness's) runs a session as before. test/daemon.py: 50 detach/attach cycles at a level fd count with no stale socket, kill -9 and Adopt, and nothing left; --gui the same for a window. test/fs.py: a forked session's socket is found by its own pid, and a hangup leaves a kept session running. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat (limited to 'src/main.zig')
-rw-r--r--src/main.zig137
1 files changed, 100 insertions, 37 deletions
diff --git a/src/main.zig b/src/main.zig
index 4e6b49bb..803ff4da 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -2,6 +2,7 @@ const std = @import("std");
const builtin = @import("builtin");
const pardes = @import("pardes.zig");
const ninep_io = @import("9p_io.zig");
+const daemon = @import("daemon.zig");
const is_emscripten = builtin.os.tag == .emscripten;
@@ -84,22 +85,20 @@ const help_text =
\\ --9p-quic=<dial> also serve at quic!<numeric-ip>!<port> (-Dquic=true).
\\ --mount=<name>=<dial> mount a 9P session or Unix/TCP/QUIC endpoint under /n/<name>.
\\ Repeat for more mounts; os and self are reserved.
- \\ --detach run this session with NO terminal of its own,
- \\ serving frontends over a unix socket beside its
- \\ 9P socket. The core, the panes and the
- \\ undo history outlive every frontend that attaches
- \\ --detach=<name> ...named <name> rather than this process's pid, so
- \\ a frontend can say which session it wants. One
- \\ path component: no '/' and nothing empty
- \\ --attach become a frontend of the one detached session
- \\ that is running: draw its screen and send it
- \\ input, and nothing else — the session owns its
- \\ pane shells, its files and its watches. Works in
- \\ both the terminal and the SDL window build.
- \\ Several frontends may be attached at once and all
- \\ see the same screen
- \\ --attach=<name> ...of the session called <name>, which is what to
- \\ use when more than one is running
+ \\ --detach run this session with no terminal (no window)
+ \\ until one attaches; its panes, shells and files
+ \\ stay. Detach, or a terminal that closes, leaves
+ \\ any session so. One `pardes --daemon` per user
+ \\ keeps them (PARDES_DAEMON=off: none)
+ \\ --detach=<name> ...named <name> rather than this process's pid,
+ \\ as --9p names it. One path component: no '/'
+ \\ and nothing empty
+ \\ --attach show the one detached session here: this
+ \\ terminal for `pardes`, a window again for
+ \\ `pardes-gui`, each of its own kind. Returns when
+ \\ the session detaches or ends
+ \\ --attach=<name> ...the session called <name> (its --9p or
+ \\ --detach name, else its pid)
\\ --geometry=WxH[+X+Y] the window's size in points, and where it goes
\\ where the display lets a window say (X11)
\\ -h, --help show this help and exit
@@ -316,7 +315,7 @@ fn emscriptenMain(argc: c_int, argv: [*]?[*:0]u8) callconv(.c) c_int {
// no argv in the browser: options stay default, state comes from the dump, and
// there is no session to attach to — a browser tab has no unix socket.
fn webMain() !void {
- try @import("gui/gui.zig").run(.{}, .{}, null);
+ try @import("gui/gui.zig").run(.{}, .{}, false);
}
// init.gpa, what the tty, gui and detached shells allocate from, is their
@@ -335,6 +334,8 @@ fn nativeMain(std_init: std.process.Init) !void {
var mounts_len: usize = 0;
const arena = init.arena.allocator();
const args = try init.minimal.args.toSlice(arena);
+ // The per-user daemon a session started (daemon.zig): nothing else.
+ if (comptime daemon.supported) if (args.len == 2 and std.mem.eql(u8, args[1], "--daemon")) daemon.serve();
var session_only = true;
var new_session = false;
var explicit_tty = false;
@@ -713,30 +714,57 @@ fn nativeMain(std_init: std.process.Init) !void {
opts.config_dir = found.dir;
opts.store_path = storePath(init.io, arena, init.environ_map);
if (found.dir) |d| @import("crash.zig").setDir(d);
+ if (attach) |name| attachTo(init.io, name);
if (detach) |name| {
- const named = if (name.len != 0)
- name
- else
- try std.fmt.allocPrint(arena, "{d}", .{@as(u32, @intCast(std.c.getpid()))});
- // Said plainly, never a Zig error trace: a name another session's
+ // Said plainly, never a Zig error trace: a name a live session's
// socket holds already (a plain session is named by its pid too).
- return @import("detached/server.zig").run(init, opts, named) catch |err| {
- var words: [128]u8 = undefined;
+ if (name.len != 0 and ninep_io.taken(name)) {
var said: [512]u8 = undefined;
- const why = if (err == error.ListenFailed)
- "its socket is taken: another session (a plain one is named by its pid) holds that name; choose another"
- else
- pardes.Messages.errorWords(err, &words);
- std.Io.File.stderr().writeStreamingAll(init.io, std.fmt.bufPrint(&said, "pardes: --detach={s}: {s}\n", .{ named, why }) catch "pardes: --detach failed\n") catch {};
+ std.Io.File.stderr().writeStreamingAll(init.io, std.fmt.bufPrint(&said, "pardes: a session named {s} is already running\n", .{name}) catch "pardes: a session of that name is already running\n") catch {};
std.process.exit(1);
- };
+ }
+ if (opts.ninep_name.len == 0) opts.ninep_name = name;
+ // Nobody's size yet: one roomy enough for a script's panes; `size`
+ // sets another, and an attached terminal or window its own.
+ opts.cols = 160;
+ opts.rows = 50;
}
- if (attach != null and pardes.platform != .tty and pardes.platform != .gui) {
- try std.Io.File.stderr().writeStreamingAll(init.io, "pardes: --attach needs the tty or gui shell\n");
- std.process.exit(1);
+ const kind: daemon.Kind = if (pardes.platform == .gui) .gui else .tty;
+ var term: @import("tty/tty.zig").Term = if (detach != null) .none else .open;
+ if (daemon.wanted()) {
+ if (detach != null or pardes.platform == .gui) {
+ _ = daemon.register(null, kind, opts.ninep_name, detach != null);
+ } else if (pardes.platform == .tty) fork: {
+ // A terminal's session is forked off its stub, which stays the
+ // job the shell waits on: Detach (or the terminal's end) ends
+ // the job and leaves the session running (daemon.forkSession).
+ // The daemon is reached or started first, from this small
+ // process, and the terminal opened while it is this one's.
+ const conn = daemon.connect(true) orelse break :fork;
+ const fd = std.c.open("/dev/tty", .{ .ACCMODE = .RDWR, .CLOEXEC = true, .NOCTTY = true }, @as(std.c.mode_t, 0));
+ if (fd < 0) {
+ daemon.startPending(true);
+ _ = std.c.close(conn);
+ break :fork;
+ }
+ // Started in the background, the job stops here until it is
+ // brought to the foreground, as one making its terminal raw does.
+ // std.posix's termios, not std.c's: glibc's is the bigger struct.
+ if (std.posix.tcgetattr(fd)) |tio| std.posix.tcsetattr(fd, .NOW, tio) catch {} else |_| {}
+ daemon.forkSession(conn) orelse {
+ daemon.startPending(true);
+ _ = std.c.close(fd);
+ _ = std.c.close(conn);
+ break :fork;
+ };
+ _ = daemon.register(conn, .tty, opts.ninep_name, false);
+ term = .{ .fd = fd };
+ }
}
+ defer daemon.quit();
+ errdefer daemon.tellStubExit(1);
switch (pardes.platform) {
- .tty => @import("tty/tty.zig").run(init, opts, attach) catch |err| switch (err) {
+ .tty => @import("tty/tty.zig").run(init, opts, term) catch |err| switch (err) {
// No controlling terminal (a detached pty, a daemon): said, not
// an error trace.
error.NoDevice => {
@@ -745,9 +773,45 @@ fn nativeMain(std_init: std.process.Init) !void {
},
else => return err,
},
- .gui => try @import("gui/gui.zig").run(init, opts, attach),
+ .gui => try @import("gui/gui.zig").run(init, opts, detach != null),
.web, .macos, .esp32p4 => unreachable,
}
+ daemon.tellStubExit(0);
+}
+
+/// `pardes --attach[=name]` in a terminal: this terminal handed (through
+/// the daemon) to the detached session of that name, or the only one, and
+/// this process its stub until the session leaves it. `pardes-gui
+/// --attach`: the session asked to open its window again, and done.
+fn attachTo(io: std.Io, name: []const u8) noreturn {
+ var words: [600]u8 = undefined;
+ const Say = struct {
+ fn no(o: std.Io, why: []const u8) noreturn {
+ var buf: [700]u8 = undefined;
+ std.Io.File.stderr().writeStreamingAll(o, std.fmt.bufPrint(&buf, "pardes: --attach: {s}\n", .{why}) catch "pardes: --attach failed\n") catch {};
+ std.process.exit(1);
+ }
+ };
+ if (comptime !daemon.supported) Say.no(io, "this system has no pardes daemon to attach through");
+ if (pardes.platform == .gui) switch (daemon.attach(.gui, name, &.{}, &words)) {
+ .ok => std.process.exit(0),
+ .no => |why| Say.no(io, why),
+ };
+ const fd = std.c.open("/dev/tty", .{ .ACCMODE = .RDWR, .CLOEXEC = true, .NOCTTY = true }, @as(std.c.mode_t, 0));
+ if (fd < 0) Say.no(io, "no terminal to attach: /dev/tty will not open");
+ if (std.posix.tcgetattr(fd)) |tio| std.posix.tcsetattr(fd, .NOW, tio) catch {} else |_| {}
+ var pipe: [2]std.c.fd_t = undefined;
+ if (std.c.pipe(&pipe) != 0) Say.no(io, "no pipe for the session to say when it leaves");
+ ninep_io.setCloexec(pipe[0]);
+ ninep_io.setCloexec(pipe[1]);
+ switch (daemon.attach(.tty, name, &.{ fd, pipe[1] }, &words)) {
+ .ok => |pid| {
+ _ = std.c.close(fd);
+ _ = std.c.close(pipe[1]);
+ daemon.stubWait(pid, false, pipe[0]);
+ },
+ .no => |why| Say.no(io, why),
+ }
}
fn parseCtrlKey(raw: []const u8) ?u21 {
@@ -774,8 +838,7 @@ test {
_ = @import("detached/wire.zig");
_ = @import("ShaderBuild.zig");
_ = @import("vaxis_input.zig");
- _ = @import("detached/server.zig");
- _ = @import("detached/client.zig");
+ _ = @import("daemon.zig");
_ = @import("9p_io.zig");
_ = @import("9p_io.zig").Client;
_ = @import("host_io.zig");