@@ -121,6 +121,7 @@ corresponding Unix manual entries for more information on calls.");
121121#else
122122#ifdef _MSC_VER /* Microsoft compiler */
123123#define HAVE_GETCWD 1
124+ #define HAVE_GETPPID 1
124125#define HAVE_SPAWNV 1
125126#define HAVE_EXECV 1
126127#define HAVE_PIPE 1
@@ -4363,16 +4364,65 @@ posix_setpgrp(PyObject *self, PyObject *noargs)
43634364#endif /* HAVE_SETPGRP */
43644365
43654366#ifdef HAVE_GETPPID
4367+
4368+ #ifdef MS_WINDOWS
4369+ #include <tlhelp32.h>
4370+
4371+ static PyObject *
4372+ win32_getppid ()
4373+ {
4374+ HANDLE snapshot ;
4375+ pid_t mypid ;
4376+ PyObject * result = NULL ;
4377+ BOOL have_record ;
4378+ PROCESSENTRY32 pe ;
4379+
4380+ mypid = getpid (); /* This function never fails */
4381+
4382+ snapshot = CreateToolhelp32Snapshot (TH32CS_SNAPPROCESS , 0 );
4383+ if (snapshot == INVALID_HANDLE_VALUE )
4384+ return PyErr_SetFromWindowsErr (GetLastError ());
4385+
4386+ pe .dwSize = sizeof (pe );
4387+ have_record = Process32First (snapshot , & pe );
4388+ while (have_record ) {
4389+ if (mypid == (pid_t )pe .th32ProcessID ) {
4390+ /* We could cache the ulong value in a static variable. */
4391+ result = PyLong_FromPid ((pid_t )pe .th32ParentProcessID );
4392+ break ;
4393+ }
4394+
4395+ have_record = Process32Next (snapshot , & pe );
4396+ }
4397+
4398+ /* If our loop exits and our pid was not found (result will be NULL)
4399+ * then GetLastError will return ERROR_NO_MORE_FILES. This is an
4400+ * error anyway, so let's raise it. */
4401+ if (!result )
4402+ result = PyErr_SetFromWindowsErr (GetLastError ());
4403+
4404+ CloseHandle (snapshot );
4405+
4406+ return result ;
4407+ }
4408+ #endif /*MS_WINDOWS*/
4409+
43664410PyDoc_STRVAR (posix_getppid__doc__ ,
43674411"getppid() -> ppid\n\n\
4368- Return the parent's process id." );
4412+ Return the parent's process id. If the parent process has already exited,\n\
4413+ Windows machines will still return its id; others systems will return the id\n\
4414+ of the 'init' process (1)." );
43694415
43704416static PyObject *
43714417posix_getppid (PyObject * self , PyObject * noargs )
43724418{
4419+ #ifdef MS_WINDOWS
4420+ return win32_getppid ();
4421+ #else
43734422 return PyLong_FromPid (getppid ());
4374- }
43754423#endif
4424+ }
4425+ #endif /* HAVE_GETPPID */
43764426
43774427
43784428#ifdef HAVE_GETLOGIN
0 commit comments