[Python-checkins] cpython (2.7): Issue #24303: Fix random EEXIST upon multiprocessing semaphores creation with

charles-francois.natali python-checkins at python.org
Fri Feb 12 17:39:32 EST 2016


https://hg.python.org/cpython/rev/d3662c088db8
changeset:   100232:d3662c088db8
branch:      2.7
parent:      100217:5715a6d9ff12
user:        Charles-François Natali <cf.natali at gmail.com>
date:        Fri Feb 12 22:39:21 2016 +0000
summary:
  Issue #24303: Fix random EEXIST upon multiprocessing semaphores creation with
Linux PID namespaces enabled.

files:
  Misc/NEWS                            |   3 +++
  Modules/_multiprocessing/semaphore.c |  16 ++++++++++++----
  2 files changed, 15 insertions(+), 4 deletions(-)


diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -50,6 +50,9 @@
 Library
 -------
 
+- Issue #24303: Fix random EEXIST upon multiprocessing semaphores creation with
+  Linux PID namespaces enabled.
+
 - Issue #25698: Importing module if the stack is too deep no longer replaces
   imported module with the empty one.
 
diff --git a/Modules/_multiprocessing/semaphore.c b/Modules/_multiprocessing/semaphore.c
--- a/Modules/_multiprocessing/semaphore.c
+++ b/Modules/_multiprocessing/semaphore.c
@@ -429,7 +429,7 @@
     int kind, maxvalue, value;
     PyObject *result;
     static char *kwlist[] = {"kind", "value", "maxvalue", NULL};
-    static int counter = 0;
+    int try = 0;
 
     if (!PyArg_ParseTupleAndKeywords(args, kwds, "iii", kwlist,
                                      &kind, &value, &maxvalue))
@@ -440,10 +440,18 @@
         return NULL;
     }
 
-    PyOS_snprintf(buffer, sizeof(buffer), "/mp%ld-%d", (long)getpid(), counter++);
+    /* Create a semaphore with a unique name. The bytes returned by
+     * _PyOS_URandom() are treated as unsigned long to ensure that the filename
+     * is valid (no special characters). */
+    do {
+        unsigned long suffix;
+        _PyOS_URandom((char *)&suffix, sizeof(suffix));
+        PyOS_snprintf(buffer, sizeof(buffer), "/mp%ld-%lu", (long)getpid(),
+                      suffix);
+        SEM_CLEAR_ERROR();
+        handle = SEM_CREATE(buffer, value, maxvalue);
+    } while ((handle == SEM_FAILED) && (errno == EEXIST) && (++try < 100));
 
-    SEM_CLEAR_ERROR();
-    handle = SEM_CREATE(buffer, value, maxvalue);
     /* On Windows we should fail if GetLastError()==ERROR_ALREADY_EXISTS */
     if (handle == SEM_FAILED || SEM_GET_LAST_ERROR() != 0)
         goto failure;

-- 
Repository URL: https://hg.python.org/cpython


More information about the Python-checkins mailing list