Skip to content

gh-102141: replace use of getpid on Windows with GetCurrentProcessId #102142

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Feb 24, 2023
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Use ``GetCurrentProcessId`` on Windows when ``getpid`` is unavailable. Patch by
Max Bachmann.
4 changes: 3 additions & 1 deletion Modules/_randommodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,9 @@ random_seed_time_pid(RandomObject *self)
key[0] = (uint32_t)(now & 0xffffffffU);
key[1] = (uint32_t)(now >> 32);

#ifdef HAVE_GETPID
#ifdef MS_WINDOWS_NON_DESKTOP
key[2] = (uint32_t)GetCurrentProcessId();
#elif defined(HAVE_GETPID)
key[2] = (uint32_t)getpid();
#else
key[2] = 0;
Expand Down
15 changes: 9 additions & 6 deletions Modules/posixmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -7946,7 +7946,7 @@ os_getgid_impl(PyObject *module)
#endif /* HAVE_GETGID */


#ifdef HAVE_GETPID
#if defined(HAVE_GETPID)
/*[clinic input]
os.getpid

Expand All @@ -7957,9 +7957,13 @@ static PyObject *
os_getpid_impl(PyObject *module)
/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
{
#ifdef MS_WINDOWS_NON_DESKTOP
return PyLong_FromUnsignedLong(GetCurrentProcessId());
#else
return PyLong_FromPid(getpid());
#endif
}
#endif /* HAVE_GETPID */
#endif /* defined(HAVE_GETPID) */

#ifdef NGROUPS_MAX
#define MAX_GROUPS NGROUPS_MAX
Expand Down Expand Up @@ -8265,12 +8269,11 @@ static PyObject*
win32_getppid()
{
HANDLE snapshot;
pid_t mypid;
PyObject* result = NULL;
BOOL have_record;
PROCESSENTRY32 pe;

mypid = getpid(); /* This function never fails */
DWORD mypid = GetCurrentProcessId(); /* This function never fails */

snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE)
Expand All @@ -8279,9 +8282,9 @@ win32_getppid()
pe.dwSize = sizeof(pe);
have_record = Process32First(snapshot, &pe);
while (have_record) {
if (mypid == (pid_t)pe.th32ProcessID) {
if (mypid == pe.th32ProcessID) {
/* We could cache the ulong value in a static variable. */
result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
result = PyLong_FromUnsignedLong(pe.th32ParentProcessID);
break;
}

Expand Down
3 changes: 3 additions & 0 deletions PC/pyconfig.h
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ WIN32 is still required for the locale module.
#define USE_SOCKET
#endif

#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)
#define MS_WINDOWS_NON_DESKTOP
#endif

/* Compiler specific defines */

Expand Down