Issue #14548: Make multiprocessing finalizers check pid before
running to cope with possibility of gc running just after fork.
(Backport from 3.x.)
diff --git a/Lib/multiprocessing/util.py b/Lib/multiprocessing/util.py
index d1b3d2e..092b61c 100644
--- a/Lib/multiprocessing/util.py
+++ b/Lib/multiprocessing/util.py
@@ -32,6 +32,7 @@
 # SUCH DAMAGE.
 #
 
+import os
 import itertools
 import weakref
 import atexit
@@ -184,6 +185,7 @@
         self._args = args
         self._kwargs = kwargs or {}
         self._key = (exitpriority, _finalizer_counter.next())
+        self._pid = os.getpid()
 
         _finalizer_registry[self._key] = self
 
@@ -196,9 +198,13 @@
         except KeyError:
             sub_debug('finalizer no longer registered')
         else:
-            sub_debug('finalizer calling %s with args %s and kwargs %s',
-                     self._callback, self._args, self._kwargs)
-            res = self._callback(*self._args, **self._kwargs)
+            if self._pid != os.getpid():
+                sub_debug('finalizer ignored because different process')
+                res = None
+            else:
+                sub_debug('finalizer calling %s with args %s and kwargs %s',
+                          self._callback, self._args, self._kwargs)
+                res = self._callback(*self._args, **self._kwargs)
             self._weakref = self._callback = self._args = \
                             self._kwargs = self._key = None
             return res