diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-04-19-20-22-00.gh-issue-148773.LBukI9.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-04-19-20-22-00.gh-issue-148773.LBukI9.rst new file mode 100644 index 00000000000000..cd39c59d7cef6e --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-04-19-20-22-00.gh-issue-148773.LBukI9.rst @@ -0,0 +1,4 @@ +Fixes a bug in :func:`print` which could result in a hangup signal (``SIGHUP``) +being sent to the user session under certain circumstances when printing an +empty string to unbuffered stdout, e.g. if ``python3 -u`` is used or the +:envvar:`PYTHONUNBUFFERED` environment variable is set. diff --git a/Python/fileutils.c b/Python/fileutils.c index 0c1766b8804500..743a66b295d30a 100644 --- a/Python/fileutils.c +++ b/Python/fileutils.c @@ -1923,7 +1923,7 @@ _Py_read(int fd, void *buf, size_t count) static Py_ssize_t _Py_write_impl(int fd, const void *buf, size_t count, int gil_held) { - Py_ssize_t n; + Py_ssize_t n = 0; int err; int async_err = 0; @@ -1970,7 +1970,11 @@ _Py_write_impl(int fd, const void *buf, size_t count, int gil_held) c /= 2; } while (c > 0); #else - n = write(fd, buf, count); + /* Only call write() if there is something to write as + * writing 0 bytes to a non-regular file is an undefined behaviour. */ + if (count > 0) { + n = write(fd, buf, count); + } #endif /* save/restore errno because PyErr_CheckSignals() * and PyErr_SetFromErrno() can modify it */ @@ -1996,7 +2000,11 @@ _Py_write_impl(int fd, const void *buf, size_t count, int gil_held) c /= 2; } while (c > 0); #else - n = write(fd, buf, count); + /* Only call write() if there is something to write as + * writing 0 bytes to a non-regular file is an undefined behaviour. */ + if (count > 0) { + n = write(fd, buf, count); + } #endif err = errno; } while (n < 0 && err == EINTR);