szn

Bug 487 — runServerDaemon closes fd 0 twice

487. open("/dev/null") returns fd 0, then close(dev_null) closes stdin

Severity: HIGH (daemon ends up with fd 0 closed) Status: ✅ FIXED Files: src/main.zig:435-450

Problem

_ = c.close(0);
_ = c.close(1);
_ = c.close(2);
const dev_null = c.open("/dev/null", c.O.RDWR, 0); // == 0, deterministically
...
_ = c.dup2(dev_null, 0); // no-op
_ = c.dup2(dev_null, 1);
_ = c.dup2(dev_null, 2);
_ = c.close(dev_null);    // closes fd 0 again!

After closing 0/1/2, open deterministically returns the lowest free fd — 0. The dup2(dev_null, 0) is then a no-op, and close(dev_null) closes fd 0 a second time. The daemonized server runs its whole lifetime with stdin closed. Any later open() returns fd 0, so a file opened by server code can alias fd 0 and reads/writes intended for stdin (or that file) go to the wrong place.

Proposed Fix

Only close when it’s actually a spare fd:

if (dev_null > 2) _ = c.close(dev_null);

Or open /dev/null three times / use fcntl(F_DUPFD, 3) semantics. A regression test can assert fds 0/1/2 are all open and distinct after daemonization.

Resolution

Replaced manual closing of fds 0-2 and unconditional close(dev_null) with redirectStdioToDevNull() in src/main.zig. redirectStdioToDevNull opens /dev/null, duplicates it across fds 0, 1, 2 via dup2, and only closes dev_null if dev_null > 2.

Tests: redirectStdioToDevNull leaves fds 0, 1, 2 open and valid — bug #487 tests in a child process that fds 0, 1, and 2 remain open and valid after redirection.