diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-20 04:16:02 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-20 04:25:21 -0300 |
| commit | 2fadb864051f5afc062606a898d821b702a1692c (patch) | |
| tree | 36a5164d90e991ae30a330d48fe26828332b63dd | |
| parent | 6e8735895d04c0073eb28cc1a2f431a2ba587e9d (diff) | |
| download | pardes-2fadb864051f5afc062606a898d821b702a1692c.tar.gz pardes-2fadb864051f5afc062606a898d821b702a1692c.zip | |
launch: `pardes new --detach[=NAME]` forks the session off and returns once it is registered and listening (the last-step design's Z1, 2.2 F's second half): exit 0 and the name on stdout, the session in a session of its own (setsid, stdin /dev/null, its stdout and stderr the launch's until it runs, so a failed start still says why there and its status is the launch's), by the stub's own wait with one word more (`r<name>`, daemon.zig `launch`/`launched`, told from the session loop after its frontend's start); the flag alone (`pardes --detach=NAME`, what every harness and a supervisor runs) is still the session itself; test/daemon.py `launch` (plain and `--launch`) failing first on the base (not returned after 15 s: the launch was the session), then 0.12-0.22 s; help new and docs/typ/command-line.txt say so
Co-Authored-By: Claude Opus <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
| -rw-r--r-- | docs/typ/command-line.txt | 6 | ||||
| -rw-r--r-- | runtime/daemon.zig | 57 | ||||
| -rw-r--r-- | runtime/main.zig | 12 | ||||
| -rw-r--r-- | runtime/session.zig | 2 | ||||
| -rw-r--r-- | test/daemon.py | 72 |
5 files changed, 145 insertions, 4 deletions
diff --git a/docs/typ/command-line.txt b/docs/typ/command-line.txt index 3c73fed4..0ced145f 100644 --- a/docs/typ/command-line.txt +++ b/docs/typ/command-line.txt @@ -95,8 +95,10 @@ See also: ps, attach Start a session here, even in a pane of another: in this terminal for pardes, a window for pardes-gui, or with --detach none until one -attaches. Bare `pardes` takes the same flags, and starts one unless -it is in a pane (where it hands its FILE to that session). +attaches, which returns once the session runs and prints its name. +Bare `pardes` takes the same flags, and starts one unless it is in a +pane (where it hands its FILE to that session); its --detach is the +session itself, until it ends (a supervisor's way). Usage: pardes new [flags] [FILE] diff --git a/runtime/daemon.zig b/runtime/daemon.zig index 80e1cc09..a2e890f9 100644 --- a/runtime/daemon.zig +++ b/runtime/daemon.zig @@ -600,6 +600,12 @@ fn stubWait(session: libc.pid_t, pipe: c_int) noreturn { const said = buf[0..len]; const out = std.Io.File.stderr(); const io = std.Io.Threaded.global_single_threaded.io(); + // `new --detach`'s session runs (`launched`): its name, for a script. + if (said.len > 0 and said[0] == 'r') { + var text: [520]u8 = undefined; + std.Io.File.stdout().writeStreamingAll(io, std.fmt.bufPrint(&text, "{s}\n", .{said[1..]}) catch said[1..]) catch {}; + libc._exit(0); + } if (said.len > 0 and said[0] == 'd') { var text: [700]u8 = undefined; const who = said[1..]; @@ -695,6 +701,57 @@ pub fn forkSession(conn: c_int) ?void { stubWait(pid, pipe[0]); } +/// `pardes new --detach`: the session forked off in a session of its own, +/// its stdin /dev/null, and this process its stub until the session runs +/// (`launched`): it then prints the name and exits 0, or with the +/// session's status if it ended first. Returns in the session, called +/// `named` (else by its pid); when no fork can be made, here, which is +/// then the session. +pub fn launch(named: []const u8) void { + var pipe: [2]c_int = undefined; + if (libc.pipe(&pipe) != 0) return; + ninep_io.setCloexec(pipe[0]); + ninep_io.setCloexec(pipe[1]); + const pid = libc.fork(); + if (pid < 0) { + _ = libc.close(pipe[0]); + _ = libc.close(pipe[1]); + return; + } + if (pid == 0) { + _ = libc.close(pipe[0]); + _ = libc.setsid(); + const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(libc.mode_t, 0)); + if (null_fd >= 0) _ = libc.dup2(null_fd, 0); + if (null_fd > 0) _ = libc.close(null_fd); + stub = pipe[1]; + launching = true; + setName(named); + return; + } + _ = libc.close(pipe[1]); + stubWait(pid, pipe[0]); +} + +/// Forked by `launch`, and its stub not told yet. +var launching = false; + +/// The session of a `new --detach` runs: registered (the daemon took its +/// hello, when there is one) and listening. Its stub told, with its name; +/// its stdout and stderr, still the launch's until now, let go. +pub fn launched() void { + if (!launching) return; + launching = false; + _ = kept(); + tellStub(stub, "r{s}", .{name()}); + stub = -1; + const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR, .CLOEXEC = true }, @as(libc.mode_t, 0)); + if (null_fd < 0) return; + _ = libc.dup2(null_fd, 1); + _ = libc.dup2(null_fd, 2); + if (null_fd > 2) _ = libc.close(null_fd); +} + // ---- the daemon ---- const Conn = struct { diff --git a/runtime/main.zig b/runtime/main.zig index a791ffec..24ed1456 100644 --- a/runtime/main.zig +++ b/runtime/main.zig @@ -323,8 +323,10 @@ const cmds = std.EnumArray(Cmd, Doc).init(.{ .doc = \\Start a session here, even in a pane of another: in this terminal for \\pardes, a window for pardes-gui, or with --detach none until one - \\attaches. Bare `pardes` takes the same flags, and starts one unless - \\it is in a pane (where it hands its FILE to that session). + \\attaches, which returns once the session runs and prints its name. + \\Bare `pardes` takes the same flags, and starts one unless it is in a + \\pane (where it hands its FILE to that session); its --detach is the + \\session itself, until it ends (a supervisor's way). , .examples = &.{ .{ "pardes new", "a session here, its shell pane in tty mode" }, @@ -1157,6 +1159,8 @@ fn nativeMain(std_init: std.process.Init) !void { const resuming = upgrade.resumed != null; var session_only = true; var new_session = false; + // `pardes new`: with --detach it returns once the session runs. + var new_verb = false; var explicit_tty = false; var detach: ?[]const u8 = null; var attach: ?[]const u8 = null; @@ -1168,6 +1172,7 @@ fn nativeMain(std_init: std.process.Init) !void { if (!resuming and args.len > 1) if (std.meta.stringToEnum(Cmd, args[1])) |cmd| switch (cmd) { .new => { new_session = true; + new_verb = true; i = 2; }, .attach => { @@ -1537,6 +1542,9 @@ fn nativeMain(std_init: std.process.Init) !void { // socket holds already (a plain session is named by its pid too). if (name.len != 0 and !resuming and ninep_io.taken(name)) die(init.io, "a session named {s} is already running", .{name}); if (opts.ninep_name.len == 0) opts.ninep_name = name; + // `new --detach` forks the session and returns once it runs; the + // flag alone is the session itself (a supervisor's, a harness's). + if (new_verb and !resuming) daemon.launch(opts.ninep_name); // Said where it was started (stderr, as the log says it): no pane // anyone sees would show it. The session runs on, with no 9P. var pid_buf: [16]u8 = undefined; diff --git a/runtime/session.zig b/runtime/session.zig index fdd72c2b..6b359eef 100644 --- a/runtime/session.zig +++ b/runtime/session.zig @@ -113,6 +113,8 @@ pub fn Loop(comptime Frontend: type) type { l.ptys.start(l.core); l.watches.start(); try fe.start(&l); + // A `new --detach`'s launch returns now. + daemon.launched(); while (!l.core.quit) { pardes.turn.bump(&pardes.turn.restores); diff --git a/test/daemon.py b/test/daemon.py index d134732b..5214bb00 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -25,6 +25,8 @@ private HOME and runtime directory: `ssh -L` forwards, say), timed python3 -B test/daemon.py --clients <pardes> the replica clients alone + python3 -B test/daemon.py --launch <pardes> + `pardes new --detach` returns once its session runs python3 -B test/daemon.py --relink <pardes> the daemon killed: its sessions register again with the next python3 -B test/daemon.py --far <pardes> @@ -526,6 +528,73 @@ def clients(binary): shutil.rmtree(root, ignore_errors=True) +def launch(binary): + """`pardes new --detach=NAME` returns once its session is registered + and listening: exit 0, the name on stdout, the session a process of its + own in a session of its own, listed by `ps` and answering 9P at once; + bare `--detach`, its pid is its name; a name taken is refused in words, + exit 1; `pardes --detach=NAME` (no `new`) is still the session itself; + nothing left behind.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rl-', dir=scratch)) + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} + env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), + TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + (root / 'notes.txt').write_text('notes\n') + + def cli(*args, timeout=30): + return subprocess.run([binary, *args], env=env, cwd=root, capture_output=True, timeout=timeout, + stdin=subprocess.DEVNULL) + + def status_pid(name): + with Client(root / f'pardes-9p-{name}.sock') as c: + return int(dict(line.split(maxsplit=1) for line in c.read('/status').decode().splitlines())['pid']) + + try: + t0 = time.monotonic() + try: + out = cli('new', '--detach=work', 'notes.txt', timeout=15) + except subprocess.TimeoutExpired: + raise AssertionError(f'launch: `new --detach=work` had not returned after {time.monotonic() - t0:.1f} s') + took = time.monotonic() - t0 + assert out.returncode == 0 and out.stdout == b'work\n', out + # Registered and listening when it returned: no wait here. + assert (root / 'pardes-9p-work.sock').exists(), list(root.iterdir()) + pid = status_pid('work') + listed = cli('ps').stdout.decode() + assert f'session work {pid} (tty, detached)' in listed, listed + assert alive(pid) and os.getsid(pid) == pid, (pid, os.getsid(pid)) + out = cli('new', '--detach') + assert out.returncode == 0 and out.stdout.strip().isdigit(), out + unnamed = int(out.stdout) + assert status_pid(str(unnamed)) == unnamed and f'session {unnamed} {unnamed} (tty, detached)' in cli('ps').stdout.decode() + taken = cli('new', '--detach=work') + assert taken.returncode == 1 and taken.stderr == b'pardes: a session named work is already running\n', taken + # The flag alone runs the session in this process, as a supervisor + # or a harness wants it. + fg = subprocess.Popen([binary, '--detach=fg'], env=env, cwd=root, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + wait_for('the foreground session\'s socket', (root / 'pardes-9p-fg.sock').exists) + assert status_pid('fg') == fg.pid and fg.poll() is None + print(f'launch: `new --detach=work` returned 0 in {took:.2f} s with its name, session {pid} listed and listening ' + f'in a session of its own; unnamed it said {unnamed}; a taken name refused; `--detach=fg` is its own session') + for name in ('work', str(unnamed), 'fg'): + assert cli('kill', name).returncode == 0 + fg.wait(timeout=10) + wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10) + print('launch: nothing left behind') + finally: + for p in processes(root): + try: + os.kill(p, signal.SIGKILL) + except OSError: + pass + shutil.rmtree(root, ignore_errors=True) + + def manage(binary): """`pardes --ps`, `--kill=NAME` and `--kill-all`: two detached sessions and their shells listed, one session killed outright and its shell @@ -1521,6 +1590,7 @@ def main(binary, cycles): clients(binary) far(binary) by_hash(binary) + launch(binary) manage(binary) relink(binary) shell = terminals(client)[0] @@ -2231,6 +2301,8 @@ if __name__ == '__main__': clients(sys.argv[2]) elif sys.argv[1:2] == ['--manage']: manage(sys.argv[2]) + elif sys.argv[1:2] == ['--launch']: + launch(sys.argv[2]) elif sys.argv[1:2] == ['--relink']: relink(sys.argv[2]) elif sys.argv[1:2] == ['--games']: |
