// Stdio // ===== // pipe(2), through bun:ffi, makes the two ends, and Bun.spawn starts the program: so it runs on Bun // on Linux and macOS only. function child_open(program, args) { const { errno } = require("os").constants; const argv = [str_out(program)]; for (let xs = args; xs.$ === CID(Con); xs = xs.tail) { argv.push(str_out(xs.head)); } if (argv[0] === "" || argv.some((arg) => arg.includes("\0"))) { return io_fail(errno.EINVAL); } if (process.platform === "win32" || typeof Bun === "undefined") { return io_fail(errno.ENOSYS); } const ffi = require("bun:ffi"); const libc = ffi.dlopen(process.platform === "darwin" ? "libSystem.dylib" : "libc.so.6", { pipe: { args: ["ptr"], returns: "i32" } }).symbols; const sys = io_sys(); const fs = require("fs"); const ends = []; for (let i = 0; i < 2; i += 1) { const fds = new Int32Array(2); if (libc.pipe(ffi.ptr(fds)) !== 0) { const code = sys.errno(); ends.forEach((fd) => fs.closeSync(fd)); return io_fail(code); } // F_SETFD, FD_CLOEXEC: the ends do not leak into other children. fds.forEach((fd) => sys.fcntl(fd, 2, 1)); ends.push(...fds); } const [inRead, inWrite, outRead, outWrite] = ends; let child; try { child = Bun.spawn(argv, { stdin: inRead, stdout: outWrite, stderr: "inherit" }); child.unref(); } catch (e) { ends.forEach((fd) => fs.closeSync(fd)); return io_fail(errno[e.code] ?? Math.abs(e.errno ?? errno.EIO)); } fs.closeSync(inRead); fs.closeSync(outWrite); return io_done(io_tup(child.pid, inWrite, outRead)); } io_eff(CID(open), child_open);