diff -r ae42c4576438 Python/random.c --- a/Python/random.c Mon Jan 26 13:45:04 2015 +0200 +++ b/Python/random.c Fri Feb 13 09:31:38 2015 +0100 @@ -188,6 +188,7 @@ dev_urandom_python(char *buffer, Py_ssiz int fd; Py_ssize_t n; struct stat st; + int flags; if (size <= 0) return 0; @@ -206,8 +207,15 @@ dev_urandom_python(char *buffer, Py_ssiz if (urandom_cache.fd >= 0) fd = urandom_cache.fd; else { + flags = O_RDONLY; +#ifdef O_CLOEXEC + /* On Linux kernel < 2.6.23, the flag is silently ignored: + * call fcntl() to ensure that the file descriptor non inheritable. */ + flags |= O_CLOEXEC; +#endif + Py_BEGIN_ALLOW_THREADS - fd = open("/dev/urandom", O_RDONLY); + fd = open("/dev/urandom", flags); Py_END_ALLOW_THREADS if (fd < 0) { @@ -219,6 +227,14 @@ dev_urandom_python(char *buffer, Py_ssiz PyErr_SetFromErrno(PyExc_OSError); return -1; } + + /* try to make the file descriptor non-inheritable, ignore errors */ + flags = fcntl(fd, F_GETFD); + if (flags >= 0) { + flags |= FD_CLOEXEC; + (void)fcntl(fd, F_SETFD, flags); + } + if (urandom_cache.fd >= 0) { /* urandom_fd was initialized by another thread while we were not holding the GIL, keep it. */