summaryrefslogtreecommitdiff
path: root/runtime/daemon.zig
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/daemon.zig')
-rw-r--r--runtime/daemon.zig57
1 files changed, 57 insertions, 0 deletions
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 {