Python os.O_CLOEXEC Examples

The following are 8 code examples of os.O_CLOEXEC(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: tuntap.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _openTunnel(self, name, mode):
        """
        Open the named tunnel using the given mode.

        @param name: The name of the tunnel to open.
        @type name: L{bytes}

        @param mode: Flags from L{TunnelFlags} with exactly one of
            L{TunnelFlags.IFF_TUN} or L{TunnelFlags.IFF_TAP} set.

        @return: A L{_TunnelDescription} representing the newly opened tunnel.
        """
        flags = (
            self._system.O_RDWR | self._system.O_CLOEXEC |
            self._system.O_NONBLOCK)
        config = struct.pack("%dsH" % (_IFNAMSIZ,), name, mode.value)
        fileno = self._system.open(_TUN_KO_PATH, flags)
        result = self._system.ioctl(fileno, _TUNSETIFF, config)
        return _TunnelDescription(fileno, result[:_IFNAMSIZ].strip(b'\x00')) 
Example #2
Source File: tuntap.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _openTunnel(self, name, mode):
        """
        Open the named tunnel using the given mode.

        @param name: The name of the tunnel to open.
        @type name: L{bytes}

        @param mode: Flags from L{TunnelFlags} with exactly one of
            L{TunnelFlags.IFF_TUN} or L{TunnelFlags.IFF_TAP} set.

        @return: A L{_TunnelDescription} representing the newly opened tunnel.
        """
        flags = (
            self._system.O_RDWR | self._system.O_CLOEXEC |
            self._system.O_NONBLOCK)
        config = struct.pack("%dsH" % (_IFNAMSIZ,), name, mode.value)
        fileno = self._system.open(_TUN_KO_PATH, flags)
        result = self._system.ioctl(fileno, _TUNSETIFF, config)
        return _TunnelDescription(fileno, result[:_IFNAMSIZ].strip(b'\x00')) 
Example #3
Source File: multipart.py    From py-ipfs-http-client with MIT License 5 votes vote down vote up
def _body(self):
		"""Streams the contents of the selected directory as binary chunks."""
		try:
			for type, path, relpath, name, parentfd in self.scanner:
				relpath_unicode = os.fsdecode(relpath).replace(os.path.sep, "/")
				short_path = self.name + (("/" + relpath_unicode) if relpath_unicode != "." else "")
				
				if type is filescanner.FSNodeType.FILE:
					try:
						# Only regular files and directories can be uploaded
						if parentfd is not None:
							stat_data = os.stat(name, dir_fd=parentfd, follow_symlinks=self.follow_symlinks)
						else:
							stat_data = os.stat(path, follow_symlinks=self.follow_symlinks)
						if not stat.S_ISREG(stat_data.st_mode):
							continue
						
						absolute_path = None  # type: ty.Optional[str]
						if self.abspath is not None:
							absolute_path = os.fsdecode(os.path.join(self.abspath, relpath))
						
						if parentfd is not None:
							f_path_or_desc = os.open(name, os.O_RDONLY | os.O_CLOEXEC, dir_fd=parentfd)
						else:
							f_path_or_desc = path
						# Stream file to client
						with open(f_path_or_desc, "rb") as file:
							yield from self._gen_file(short_path, absolute_path, file)
					except OSError as e:
						print(e)
						# File might have disappeared between `os.walk()` and `open()`
						pass
				elif type is filescanner.FSNodeType.DIRECTORY:
					# Generate directory as special empty file
					yield from self._gen_file(short_path, content_type="application/x-directory")
			
			yield from self._gen_end()
		finally:
			self.scanner.close() 
Example #4
Source File: utils.py    From kitty with GNU General Public License v3.0 5 votes vote down vote up
def single_instance_unix(name: str) -> bool:
    import socket
    for path in unix_socket_paths(name):
        socket_path = path.rpartition('.')[0] + '.sock'
        fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC | os.O_CLOEXEC)
        try:
            fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except OSError as err:
            if err.errno in (errno.EAGAIN, errno.EACCES):
                # Client
                s = socket.socket(family=socket.AF_UNIX)
                s.connect(socket_path)
                single_instance.socket = s
                return False
            raise
        s = socket.socket(family=socket.AF_UNIX)
        try:
            s.bind(socket_path)
        except OSError as err:
            if err.errno in (errno.EADDRINUSE, errno.EEXIST):
                os.unlink(socket_path)
                s.bind(socket_path)
            else:
                raise
        single_instance.socket = s  # prevent garbage collection from closing the socket
        atexit.register(remove_socket_file, s, socket_path)
        s.listen()
        s.set_inheritable(False)
        return True
    return False 
Example #5
Source File: jsoncomm.py    From osbuild with Apache License 2.0 5 votes vote down vote up
def new_server(cls, bind_to: str):
        """Create Server

        Create a new listener socket.

        Parameters
        ----------
        bind_to
            The socket-address to listen on for incoming client requests.
        """

        sock = None
        unlink = None
        path = os.path.split(bind_to)

        try:
            # We bind the socket and then open a directory-fd on the target
            # socket. This allows us to properly unlink the socket when the
            # server is closed. Note that sockets are never automatically
            # cleaned up on linux, nor can you bind to existing sockets.
            # We use a dirfd to guarantee this works even when you change
            # your mount points in-between.
            # Yeah, this is racy when mount-points change between the socket
            # creation and open. But then your entire socket creation is racy
            # as well. We do not guarantee atomicity, so you better make sure
            # you do not rely on it.
            sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
            sock.bind(bind_to)
            unlink = os.open(os.path.join(".", path[0]), os.O_CLOEXEC | os.O_PATH)
        except:
            if unlink is not None:
                os.close(unlink)
            if sock is not None:
                sock.close()
            raise

        return cls(sock, (unlink, path[1])) 
Example #6
Source File: utils.py    From vise with GNU General Public License v3.0 5 votes vote down vote up
def pipe2():
    try:
        read_fd, write_fd = os.pipe2(os.O_NONBLOCK | os.O_CLOEXEC)
    except AttributeError:
        import fcntl
        read_fd, write_fd = os.pipe()
        for fd in (read_fd, write_fd):
            flag = fcntl.fcntl(fd, fcntl.F_GETFD)
            fcntl.fcntl(fd, fcntl.F_SETFD, flag | fcntl.FD_CLOEXEC)
            flag = fcntl.fcntl(fd, fcntl.F_GETFL)
            fcntl.fcntl(fd, fcntl.F_SETFL, flag | os.O_NONBLOCK)
    return read_fd, write_fd 
Example #7
Source File: mkosi.py    From mkosi with GNU Lesser General Public License v2.1 5 votes vote down vote up
def open_close(path: str, flags: int, mode: int = 0o664) -> Generator[int, None, None]:
    fd = os.open(path, flags | os.O_CLOEXEC, mode)
    try:
        yield fd
    finally:
        os.close(fd) 
Example #8
Source File: zip.py    From aptsources-cleanup with MIT License 5 votes vote down vote up
def _open_directory(self, path):
		return self.exitstack.enter_context(
			FileDescriptor(path, os.O_PATH | os.O_DIRECTORY | os.O_CLOEXEC))