command: only spin on waitpid if it's non-blocking

This commit is contained in:
Will Pragnell
2023-08-30 22:02:25 -07:00
committed by Mitchell Hashimoto
parent aa9e12dac2
commit 2e54ad2cce

View File

@ -187,6 +187,7 @@ fn setupFd(src: File.Handle, target: i32) !void {
/// Wait for the command to exit and return information about how it exited.
pub fn wait(self: Command, block: bool) !Exit {
const res = if (block) std.os.waitpid(self.pid.?, 0) else res: {
// We specify NOHANG because its not our fault if the process we launch
// for the tty doesn't properly waitpid its children. We don't want
// to hang the terminal over it.
@ -194,10 +195,12 @@ pub fn wait(self: Command, block: bool) !Exit {
// doesn't have a status to report. When that happens, it is as though the
// wait call has not been performed, so we need to keep trying until we get
// a non-zero pid back, otherwise we end up with zombie processes.
var res = std.os.WaitPidResult{ .pid = 0, .status = 0 };
while (res.pid == 0) {
res = std.os.waitpid(self.pid.?, if (block) 0 else std.c.W.NOHANG);
while (true) {
const res = std.os.waitpid(self.pid.?, std.c.W.NOHANG);
if (res.pid != 0) break :res res;
}
};
return Exit.init(res.status);
}