import fcntl, os _FD_CLOEXEC = getattr(fcntl, 'FD_CLOEXEC', 1) if hasattr(os, 'O_CLOEXEC'): o_cloexec_works = None else: o_cloexec_works = False def open_cloexec(filename, open_flags): global o_cloexec_works if hasattr(os, 'O_CLOEXEC'): open_flags |= os.O_CLOEXEC fd = os.open(filename, open_flags) if hasattr(os, 'O_CLOEXEC') and o_cloexec_works: set_flags = False else: fcntl_flags = fcntl.fcntl(fd, fcntl.F_GETFD) if hasattr(os, 'O_CLOEXEC'): if o_cloexec_works is None: # Linux < 2.6.23 ignores silently the O_CLOEXEC flag o_cloexec_works = (fcntl_flags & _FD_CLOEXEC) == _FD_CLOEXEC set_flags = not o_cloexec_works else: set_flags = True if set_flags: fcntl_flags |= _FD_CLOEXEC fcntl.fcntl(fd, fcntl.F_SETFD, fcntl_flags) print("Works?", o_cloexec_works) open_cloexec('/', os.O_RDONLY) print("Works?", o_cloexec_works)