From 3175f197138d1a10b430216428174061b97d499f Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Mon, 14 Oct 2024 20:41:33 +0200 Subject: [PATCH] implement PID 0 exceptions in C --- psutil/_psbsd.py | 20 ++++---------------- psutil/arch/bsd/proc.c | 10 +++++++++- psutil/arch/openbsd/proc.c | 11 ++++++++++- 3 files changed, 23 insertions(+), 18 deletions(-) diff --git a/psutil/_psbsd.py b/psutil/_psbsd.py index d40d31c40..deffe50b0 100644 --- a/psutil/_psbsd.py +++ b/psutil/_psbsd.py @@ -911,14 +911,7 @@ def _not_implemented(self): @wrap_exceptions def open_files(self): """Return files opened by process as a list of namedtuples.""" - if OPENBSD and self.pid == 0: - try: - rawlist = cext.proc_open_files(self.pid) - except ProcessLookupError: - return [] - else: - rawlist = cext.proc_open_files(self.pid) - + rawlist = cext.proc_open_files(self.pid) return [_common.popenfile(path, fd) for path, fd in rawlist] else: @@ -931,15 +924,10 @@ def open_files(self): @wrap_exceptions def num_fds(self): """Return the number of file descriptors opened by this process.""" - if OPENBSD and self.pid == 0: - try: - return cext.proc_num_fds(self.pid) - except ProcessLookupError: - return 0 - elif NETBSD: + ret = cext.proc_num_fds(self.pid) + if NETBSD: self._assert_alive() - - return cext.proc_num_fds(self.pid) + return ret else: num_fds = _not_implemented diff --git a/psutil/arch/bsd/proc.c b/psutil/arch/bsd/proc.c index 5d353ff35..1644957ea 100644 --- a/psutil/arch/bsd/proc.c +++ b/psutil/arch/bsd/proc.c @@ -442,8 +442,16 @@ psutil_proc_open_files(PyObject *self, PyObject *args) { errno = 0; freep = kinfo_getfile(pid, &cnt); + if (freep == NULL) { -#if !defined(PSUTIL_OPENBSD) +#if defined(PSUTIL_OPENBSD) + if ((pid == 0) && (errno == ESRCH)) { + psutil_debug( + "open_files() returned ESRCH for PID 0; forcing `return []`" + ); + return py_retlist; + } +#else psutil_raise_for_pid(pid, "kinfo_getfile()"); #endif goto error; diff --git a/psutil/arch/openbsd/proc.c b/psutil/arch/openbsd/proc.c index 945e7e14e..9b4593c3e 100644 --- a/psutil/arch/openbsd/proc.c +++ b/psutil/arch/openbsd/proc.c @@ -288,8 +288,17 @@ psutil_proc_num_fds(PyObject *self, PyObject *args) { return NULL; freep = kinfo_getfile(pid, &cnt); - if (freep == NULL) + if (freep == NULL) { +#if defined(PSUTIL_OPENBSD) + if ((pid == 0) && (errno == ESRCH)) { + psutil_debug( + "num_fds() returned ESRCH for PID 0; forcing `return 0`" + ); + return Py_BuildValue("i", 0); + } +#endif return NULL; + } free(freep); return Py_BuildValue("i", cnt);