Python fcntl.fcntl() Examples

The following are 50 code examples for showing how to use fcntl.fcntl(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: electrum-martexcoin-server   Author: martexcoin   File: stratum_http.py View Source Project 6 votes vote down vote up
def __init__(self, addr, requestHandler=StratumJSONRPCRequestHandler,
                 logRequests=False, encoding=None, bind_and_activate=True,
                 address_family=socket.AF_INET):
        self.logRequests = logRequests
        StratumJSONRPCDispatcher.__init__(self, encoding)
        # TCPServer.__init__ has an extra parameter on 2.6+, so
        # check Python version and decide on how to call it
        vi = sys.version_info
        self.address_family = address_family
        if USE_UNIX_SOCKETS and address_family == socket.AF_UNIX:
            # Unix sockets can't be bound if they already exist in the
            # filesystem. The convention of e.g. X11 is to unlink
            # before binding again.
            if os.path.exists(addr):
                try:
                    os.unlink(addr)
                except OSError:
                    logging.warning("Could not unlink socket %s", addr)

        SocketServer.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)

        if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
            flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
            flags |= fcntl.FD_CLOEXEC
            fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags) 
Example 2
Project: pykit   Author: baishancloud   File: daemonize.py View Source Project 6 votes vote down vote up
def __init__(self,
                 pidfile=None,
                 stdin='/dev/null',
                 stdout='/dev/null',
                 stderr='/dev/null',
                 close_fds=False):

        self.stdin = stdin
        self.stdout = stdout
        self.stderr = stderr
        self.pidfile = pidfile or _default_pid_file()
        # NOTE: We need to open another separate file to avoid the file
        #       being reopened again.
        #       In which case, process loses file lock.
        #
        # From "man fcntl":
        # As well as being removed by an explicit F_UNLCK, record locks are
        # automatically released when the process terminates or if it
        # closes any file descriptor referring to a file on which locks
        # are held. This is bad: it means that a process can lose the locks
        # on a file like /etc/passwd or /etc/mtab when for some reason a
        # library function decides to open, read and close it.
        self.lockfile = self.pidfile + ".lock"
        self.lockfp = None
        self.close_fds = close_fds 
Example 3
Project: pykit   Author: baishancloud   File: daemonize.py View Source Project 6 votes vote down vote up
def write_pid_or_exit(self):

        self.pf = open(self.pidfile, 'w+r')
        pf = self.pf

        fd = pf.fileno()
        fcntl.fcntl(fd, fcntl.F_SETFD,
                    fcntl.fcntl(fd, fcntl.F_GETFD, 0)
                    | fcntl.FD_CLOEXEC)

        try:
            pid = os.getpid()
            logger.debug('write pid:' + str(pid))

            pf.truncate(0)
            pf.write(str(pid))
            pf.flush()
        except Exception as e:
            logger.exception('write pid failed.' + repr(e))
            sys.exit(0) 
Example 4
Project: health-mosconi   Author: GNUHealth-Mosconi   File: jsonrpc.py View Source Project 6 votes vote down vote up
def __init__(self, addr, requestHandler=SimpleJSONRPCRequestHandler,
            logRequests=True, allow_none=False, encoding=None,
            bind_and_activate=True):
        self.handlers = set()
        self.logRequests = logRequests

        SimpleJSONRPCDispatcher.__init__(self, allow_none, encoding)
        try:
            SocketServer.TCPServer.__init__(self, addr, requestHandler,
                    bind_and_activate)
        except TypeError:
            SocketServer.TCPServer.__init__(self, addr, requestHandler)

        # [Bug #1222790] If possible, set close-on-exec flag; if a
        # method spawns a subprocess, the subprocess shouldn't have
        # the listening socket open.
        if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
            flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
            flags |= fcntl.FD_CLOEXEC
            fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags) 
Example 5
Project: android3dblendermouse   Author: sketchpunk   File: serialposix.py View Source Project 6 votes vote down vote up
def _set_rs485_mode(self, rs485_settings):
            buf = array.array('i', [0] * 8)  # flags, delaytx, delayrx, padding
            try:
                fcntl.ioctl(self.fd, TIOCGRS485, buf)
                if rs485_settings is not None:
                    if rs485_settings.loopback:
                        buf[0] |= SER_RS485_RX_DURING_TX
                    else:
                        buf[0] &= ~SER_RS485_RX_DURING_TX
                    if rs485_settings.rts_level_for_tx:
                        buf[0] |= SER_RS485_RTS_ON_SEND
                    else:
                        buf[0] &= ~SER_RS485_RTS_ON_SEND
                    if rs485_settings.rts_level_for_rx:
                        buf[0] |= SER_RS485_RTS_AFTER_SEND
                    else:
                        buf[0] &= ~SER_RS485_RTS_AFTER_SEND
                    buf[1] = int(rs485_settings.delay_rts_before_send * 1000)
                    buf[2] = int(rs485_settings.delay_rts_after_send * 1000)
                else:
                    buf[0] = 0  # clear SER_RS485_ENABLED
                fcntl.ioctl(self.fd, TIOCSRS485, buf)
            except IOError as e:
                raise ValueError('Failed to set RS485 mode: %s' % (e,)) 
Example 6
Project: watchmen   Author: lycclsltt   File: agent.py View Source Project 6 votes vote down vote up
def _communicate(self):
        import fcntl
        oldflags = fcntl.fcntl(self.__inr, fcntl.F_GETFL)
        fcntl.fcntl(self.__inr, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
        while not self._exit:
            events = select([self._agent._conn, self.__inr], [], [], 0.5)
            for fd in events[0]:
                if self._agent._conn == fd:
                    data = self._agent._conn.recv(512)
                    if len(data) != 0:
                        self.__inr.send(data)
                    else:
                        self._close()
                        break
                elif self.__inr == fd:
                    data = self.__inr.recv(512)
                    if len(data) != 0:
                        self._agent._conn.send(data)
                    else:
                        self._close()
                        break
            time.sleep(io_sleep) 
Example 7
Project: microperi   Author: c0d3st0rm   File: serialposix.py View Source Project 6 votes vote down vote up
def _set_rs485_mode(self, rs485_settings):
            buf = array.array('i', [0] * 8)  # flags, delaytx, delayrx, padding
            try:
                fcntl.ioctl(self.fd, TIOCGRS485, buf)
                if rs485_settings is not None:
                    if rs485_settings.loopback:
                        buf[0] |= SER_RS485_RX_DURING_TX
                    else:
                        buf[0] &= ~SER_RS485_RX_DURING_TX
                    if rs485_settings.rts_level_for_tx:
                        buf[0] |= SER_RS485_RTS_ON_SEND
                    else:
                        buf[0] &= ~SER_RS485_RTS_ON_SEND
                    if rs485_settings.rts_level_for_rx:
                        buf[0] |= SER_RS485_RTS_AFTER_SEND
                    else:
                        buf[0] &= ~SER_RS485_RTS_AFTER_SEND
                    buf[1] = int(rs485_settings.delay_rts_before_send * 1000)
                    buf[2] = int(rs485_settings.delay_rts_after_send * 1000)
                else:
                    buf[0] = 0  # clear SER_RS485_ENABLED
                fcntl.ioctl(self.fd, TIOCSRS485, buf)
            except IOError as e:
                raise ValueError('Failed to set RS485 mode: %s' % (e,)) 
Example 8
Project: lbryum-server   Author: lbryio   File: stratum_http.py View Source Project 6 votes vote down vote up
def __init__(self, addr, requestHandler=StratumJSONRPCRequestHandler,
                 logRequests=False, encoding=None, bind_and_activate=True,
                 address_family=socket.AF_INET):
        self.logRequests = logRequests
        StratumJSONRPCDispatcher.__init__(self, encoding)
        # TCPServer.__init__ has an extra parameter on 2.6+, so
        # check Python version and decide on how to call it
        vi = sys.version_info
        self.address_family = address_family
        if USE_UNIX_SOCKETS and address_family == socket.AF_UNIX:
            # Unix sockets can't be bound if they already exist in the
            # filesystem. The convention of e.g. X11 is to unlink
            # before binding again.
            if os.path.exists(addr):
                try:
                    os.unlink(addr)
                except OSError:
                    logging.warning("Could not unlink socket %s", addr)

        SocketServer.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)

        if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
            flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
            flags |= fcntl.FD_CLOEXEC
            fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags) 
Example 9
Project: HyperGAN   Author: 255BITS   File: cli.py View Source Project 6 votes vote down vote up
def train(self):
        i=0
        if(self.args.ipython):
            fd = sys.stdin.fileno()
            fl = fcntl.fcntl(fd, fcntl.F_GETFL)
            fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)

        while(i < self.total_steps or self.total_steps == -1):
            i+=1
            start_time = time.time()
            self.step()

            if (self.args.save_every != None and
                self.args.save_every != -1 and
                self.args.save_every > 0 and
                i % self.args.save_every == 0):
                print(" |= Saving network")
                self.gan.save(self.save_file)
            if self.args.ipython:
                self.check_stdin()
            end_time = time.time() 
Example 10
Project: led   Author: rec   File: Keyboard.py View Source Project 6 votes vote down vote up
def keyboard(callback, exit='q'):
    fd = sys.stdin.fileno()

    oldterm = termios.tcgetattr(fd)
    newattr = termios.tcgetattr(fd)
    newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
    termios.tcsetattr(fd, termios.TCSANOW, newattr)

    oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

    try:
        while True:
            try:
                ch = sys.stdin.read(1)
                if ch:
                    callback(ch)
                    if ch == exit:
                        break
            except IOError:
                pass
    finally:
        termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
        fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) 
Example 11
Project: jumpscale_portal   Author: jumpscale7   File: SocketProcess.py View Source Project 6 votes vote down vote up
def restartInProcess(self, app):
        args = sys.argv[:]
        args.insert(0, sys.executable)
        apppath = j.system.fs.joinPaths(j.dirs.appDir, app)
        max_fd = 1024
        for fd in range(3, max_fd):
            try:
                flags = fcntl.fcntl(fd, fcntl.F_GETFD)
            except IOError:
                continue
            fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
        os.chdir(apppath)
        os.execv(sys.executable, args)

    # def getRedisClient(self,appname,actorname):

        # if ini.checkSection("redis"):
            # redisip=ini.getValue("redis","ipaddr")
            # redisport=ini.getValue("redis","port")
            #redisclient=redis.StrictRedis(host=redisip, port=int(redisport), db=0)
        # else:
            # redisclient=None
        # return redisclient 
Example 12
Project: fdslight   Author: fdslight   File: tundev.py View Source Project 6 votes vote down vote up
def init_func(self, creator_fd, tun_dev_name, *args, **kwargs):
        """
        :param creator_fd:
        :param tun_dev_name:tun ????
        :param subnet:?????????????
        """
        tun_fd = self.__create_tun_dev(tun_dev_name)

        if tun_fd < 3:
            print("error:create tun device failed:%s" % tun_dev_name)
            sys.exit(-1)

        self.__creator_fd = creator_fd
        self.__qos = simple_qos.qos(simple_qos.QTYPE_DST)

        self.set_fileno(tun_fd)
        fcntl.fcntl(tun_fd, fcntl.F_SETFL, os.O_NONBLOCK)
        self.dev_init(tun_dev_name, *args, **kwargs)

        return tun_fd 
Example 13
Project: Liljimbo-Chatbot   Author: chrisjim316   File: server.py View Source Project 6 votes vote down vote up
def __init__(self, host='127.0.0.1', port=23, application=None, encoding='utf-8'):
        assert isinstance(host, text_type)
        assert isinstance(port, int)
        assert isinstance(application, TelnetApplication)
        assert isinstance(encoding, text_type)

        self.host = host
        self.port = port
        self.application = application
        self.encoding = encoding

        self.connections = set()

        self._calls_from_executor = []

        # Create a pipe for inter thread communication.
        self._schedule_pipe = os.pipe()
        fcntl.fcntl(self._schedule_pipe[0], fcntl.F_SETFL, os.O_NONBLOCK) 
Example 14
Project: Liljimbo-Chatbot   Author: chrisjim316   File: posix.py View Source Project 6 votes vote down vote up
def __init__(self, inputhook=None, selector=AutoSelector):
        assert inputhook is None or callable(inputhook)
        assert issubclass(selector, Selector)

        self.running = False
        self.closed = False
        self._running = False
        self._callbacks = None

        self._calls_from_executor = []
        self._read_fds = {} # Maps fd to handler.
        self.selector = selector()

        # Create a pipe for inter thread communication.
        self._schedule_pipe = os.pipe()
        fcntl.fcntl(self._schedule_pipe[0], fcntl.F_SETFL, os.O_NONBLOCK)

        # Create inputhook context.
        self._inputhook_context = InputHookContext(inputhook) if inputhook else None 
Example 15
Project: pycos   Author: pgiri   File: asyncfile.py View Source Project 5 votes vote down vote up
def __init__(self, fd):
            """'fd' is either a file object (e.g., obtained with 'open')
            or a file number (e.g., obtained with socket's fileno()).
            """
            if hasattr(fd, 'fileno'):
                self._fd = fd
                self._fileno = fd.fileno()
            elif isinstance(fd, int):
                self._fd, self._fileno = None, self._fd
            else:
                raise ValueError('invalid file descriptor')
            self._pycos = Pycos.scheduler()
            if self._pycos:
                self._notifier = self._pycos._notifier
                if hasattr(fd, '_fileno'):  # assume it is AsyncSocket
                    self._notifier.unregister(fd)
            else:
                self._notifier = None
            self._timeout = None
            self._read_task = None
            self._read_fn = None
            self._write_task = None
            self._write_fn = None
            self._buflist = []
            flags = fcntl.fcntl(self._fileno, fcntl.F_GETFL)
            fcntl.fcntl(self._fileno, fcntl.F_SETFL, flags | os.O_NONBLOCK) 
Example 16
Project: pycos   Author: pgiri   File: asyncfile.py View Source Project 5 votes vote down vote up
def __init__(self, fd):
            """'fd' is either a file object (e.g., obtained with 'open')
            or a file number (e.g., obtained with socket's fileno()).
            """
            if hasattr(fd, 'fileno'):
                self._fd = fd
                self._fileno = fd.fileno()
            elif isinstance(fd, int):
                self._fd, self._fileno = None, self._fd
            else:
                raise ValueError('invalid file descriptor')
            self._pycos = Pycos.scheduler()
            if self._pycos:
                self._notifier = self._pycos._notifier
                if hasattr(fd, '_fileno'):  # assume it is AsyncSocket
                    self._notifier.unregister(fd)
            else:
                self._notifier = None
            self._timeout = None
            self._read_task = None
            self._read_fn = None
            self._write_task = None
            self._write_fn = None
            self._buflist = []
            flags = fcntl.fcntl(self._fileno, fcntl.F_GETFL)
            fcntl.fcntl(self._fileno, fcntl.F_SETFL, flags | os.O_NONBLOCK) 
Example 17
Project: kinect-2-libras   Author: inessadl   File: subprocess.py View Source Project 5 votes vote down vote up
def _set_cloexec_flag(self, fd, cloexec=True):
            try:
                cloexec_flag = fcntl.FD_CLOEXEC
            except AttributeError:
                cloexec_flag = 1

            old = fcntl.fcntl(fd, fcntl.F_GETFD)
            if cloexec:
                fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
            else:
                fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag) 
Example 18
Project: kinect-2-libras   Author: inessadl   File: posixfile.py View Source Project 5 votes vote down vote up
def flags(self, *which):
        import fcntl, os

        if which:
            if len(which) > 1:
                raise TypeError, 'Too many arguments'
            which = which[0]
        else: which = '?'

        l_flags = 0
        if 'n' in which: l_flags = l_flags | os.O_NDELAY
        if 'a' in which: l_flags = l_flags | os.O_APPEND
        if 's' in which: l_flags = l_flags | os.O_SYNC

        file = self._file_

        if '=' not in which:
            cur_fl = fcntl.fcntl(file.fileno(), fcntl.F_GETFL, 0)
            if '!' in which: l_flags = cur_fl & ~ l_flags
            else: l_flags = cur_fl | l_flags

        l_flags = fcntl.fcntl(file.fileno(), fcntl.F_SETFL, l_flags)

        if 'c' in which:
            arg = ('!' not in which)    # 0 is don't, 1 is do close on exec
            l_flags = fcntl.fcntl(file.fileno(), fcntl.F_SETFD, arg)

        if '?' in which:
            which = ''                  # Return current flags
            l_flags = fcntl.fcntl(file.fileno(), fcntl.F_GETFL, 0)
            if os.O_APPEND & l_flags: which = which + 'a'
            if fcntl.fcntl(file.fileno(), fcntl.F_GETFD, 0) & 1:
                which = which + 'c'
            if os.O_NDELAY & l_flags: which = which + 'n'
            if os.O_SYNC & l_flags: which = which + 's'
            return which 
Example 19
Project: kinect-2-libras   Author: inessadl   File: SimpleXMLRPCServer.py View Source Project 5 votes vote down vote up
def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
                 logRequests=True, allow_none=False, encoding=None, bind_and_activate=True):
        self.logRequests = logRequests

        SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
        SocketServer.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)

        # [Bug #1222790] If possible, set close-on-exec flag; if a
        # method spawns a subprocess, the subprocess shouldn't have
        # the listening socket open.
        if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
            flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
            flags |= fcntl.FD_CLOEXEC
            fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags) 
Example 20
Project: kinect-2-libras   Author: inessadl   File: tempfile.py View Source Project 5 votes vote down vote up
def _set_cloexec(fd):
        try:
            flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0)
        except IOError:
            pass
        else:
            # flags read successfully, modify
            flags |= _fcntl.FD_CLOEXEC
            _fcntl.fcntl(fd, _fcntl.F_SETFD, flags) 
Example 21
Project: kinect-2-libras   Author: inessadl   File: asyncore.py View Source Project 5 votes vote down vote up
def __init__(self, fd, map=None):
            dispatcher.__init__(self, None, map)
            self.connected = True
            try:
                fd = fd.fileno()
            except AttributeError:
                pass
            self.set_file(fd)
            # set it to non-blocking mode
            flags = fcntl.fcntl(fd, fcntl.F_GETFL, 0)
            flags = flags | os.O_NONBLOCK
            fcntl.fcntl(fd, fcntl.F_SETFL, flags) 
Example 22
Project: Flask_Blog   Author: sugarguo   File: threadedserver.py View Source Project 5 votes vote down vote up
def setCloseOnExec(sock):
        fcntl.fcntl(sock.fileno(), fcntl.F_SETFD, fcntl.FD_CLOEXEC) 
Example 23
Project: Flask_Blog   Author: sugarguo   File: preforkserver.py View Source Project 5 votes vote down vote up
def setCloseOnExec(sock):
        fcntl.fcntl(sock.fileno(), fcntl.F_SETFD, fcntl.FD_CLOEXEC)

# If running Python < 2.4, require eunuchs module for socket.socketpair().
# See <http://www.inoi.fi/open/trac/eunuchs>. 
Example 24
Project: Flask_Blog   Author: sugarguo   File: singleserver.py View Source Project 5 votes vote down vote up
def setCloseOnExec(sock):
        fcntl.fcntl(sock.fileno(), fcntl.F_SETFD, fcntl.FD_CLOEXEC) 
Example 25
Project: code   Author: ActiveState   File: recipe-52296.py View Source Project 5 votes vote down vote up
def makeNonBlocking(fd):
    fl = fcntl.fcntl(fd, FCNTL.F_GETFL)
    try:
	fcntl.fcntl(fd, FCNTL.F_SETFL, fl | FCNTL.O_NDELAY)
    except AttributeError:
	fcntl.fcntl(fd, FCNTL.F_SETFL, fl | FCNTL.FNDELAY) 
Example 26
Project: shadowsocksR-b   Author: hao35954514   File: daemon.py View Source Project 5 votes vote down vote up
def write_pid_file(pid_file, pid):
    import fcntl
    import stat

    try:
        fd = os.open(pid_file, os.O_RDWR | os.O_CREAT,
                     stat.S_IRUSR | stat.S_IWUSR)
    except OSError as e:
        shell.print_exception(e)
        return -1
    flags = fcntl.fcntl(fd, fcntl.F_GETFD)
    assert flags != -1
    flags |= fcntl.FD_CLOEXEC
    r = fcntl.fcntl(fd, fcntl.F_SETFD, flags)
    assert r != -1
    # There is no platform independent way to implement fcntl(fd, F_SETLK, &fl)
    # via fcntl.fcntl. So use lockf instead
    try:
        fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 0, 0, os.SEEK_SET)
    except IOError:
        r = os.read(fd, 32)
        if r:
            logging.error('already started at pid %s' % common.to_str(r))
        else:
            logging.error('already started')
        os.close(fd)
        return -1
    os.ftruncate(fd, 0)
    os.write(fd, common.to_bytes(str(pid)))
    return 0 
Example 27
Project: electrum-martexcoin-server   Author: martexcoin   File: stratum_http.py View Source Project 5 votes vote down vote up
def __init__(self, addr, certfile, keyfile,
                 requestHandler=SSLRequestHandler,
                 logRequests=False, encoding=None, bind_and_activate=True,
                 address_family=socket.AF_INET):

        self.logRequests = logRequests
        StratumJSONRPCDispatcher.__init__(self, encoding)
        # TCPServer.__init__ has an extra parameter on 2.6+, so
        # check Python version and decide on how to call it
        vi = sys.version_info
        self.address_family = address_family
        if USE_UNIX_SOCKETS and address_family == socket.AF_UNIX:
            # Unix sockets can't be bound if they already exist in the
            # filesystem. The convention of e.g. X11 is to unlink
            # before binding again.
            if os.path.exists(addr):
                try:
                    os.unlink(addr)
                except OSError:
                    logging.warning("Could not unlink socket %s", addr)

        SSLTCPServer.__init__(self, addr, certfile, keyfile, requestHandler, bind_and_activate)

        if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
            flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
            flags |= fcntl.FD_CLOEXEC
            fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags) 
Example 28
Project: beastcraft-telemetry   Author: ab77   File: monitor.py View Source Project 5 votes vote down vote up
def main(user='admin', host=None, port=22, iface=None, backup=None, gwip=None):
    # assume interface is online
    iface_status = 'alive'
    # run the shell as a subprocess:
    p = Popen(['ssh', '%[email protected]%s' % (user, host)],
              stdin = PIPE, stdout = PIPE, stderr = PIPE, shell = False)
    # set the O_NONBLOCK flag of p.stdout file descriptor:
    flags = fcntl(p.stdout, F_GETFL) # get current p.stdout flags
    fcntl(p.stdout, F_SETFL, flags | O_NONBLOCK)
    # get the output
    while True:
        # issue command:
        p.stdin.write('diag sys link-monitor status %s\n' % iface)
        # let the shell output the result:
        sleep(5)
        try:
            line = read(p.stdout.fileno(), 1024)
            if line.split()[0] == 'Link':
                print '%s %s %s' % (line.split()[2], line.split()[3], line.split()[4])
                if line.split()[4] == 'die' and iface_status == 'alive':
                    iface_status = line.split()[4]
                    set_defaut_route(p=p, iface=backup, gw=args.gwip)
                if line.split()[4] == 'alive' and iface_status == 'die':
                    set_defaut_route(p=p, iface=iface)
                    iface_status = line.split()[4]
                    
        except OSError:
            # the os throws an exception if there is no data
            sleep(5) 
Example 29
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: twisted_test.py View Source Project 5 votes vote down vote up
def _set_nonblocking(self, fd):
        flags = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) 
Example 30
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: posix.py View Source Project 5 votes vote down vote up
def set_close_exec(fd):
    flags = fcntl.fcntl(fd, fcntl.F_GETFD)
    fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC) 
Example 31
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: posix.py View Source Project 5 votes vote down vote up
def _set_nonblocking(fd):
    flags = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) 
Example 32
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: twisted_test.py View Source Project 5 votes vote down vote up
def _set_nonblocking(self, fd):
        flags = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) 
Example 33
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: posix.py View Source Project 5 votes vote down vote up
def set_close_exec(fd):
    flags = fcntl.fcntl(fd, fcntl.F_GETFD)
    fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC) 
Example 34
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: twisted_test.py View Source Project 5 votes vote down vote up
def _set_nonblocking(self, fd):
        flags = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) 
Example 35
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: posix.py View Source Project 5 votes vote down vote up
def set_close_exec(fd):
    flags = fcntl.fcntl(fd, fcntl.F_GETFD)
    fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC) 
Example 36
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: posix.py View Source Project 5 votes vote down vote up
def _set_nonblocking(fd):
    flags = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) 
Example 37
Project: geekcloud   Author: Mr-Linus   File: connect.py View Source Project 5 votes vote down vote up
def get_win_size():
        """
        This function use to get the size of the windows!
        ??terminal????
        """
        if 'TIOCGWINSZ' in dir(termios):
            TIOCGWINSZ = termios.TIOCGWINSZ
        else:
            TIOCGWINSZ = 1074295912L
        s = struct.pack('HHHH', 0, 0, 0, 0)
        x = fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s)
        return struct.unpack('HHHH', x)[0:2] 
Example 38
Project: pypilot   Author: pypilot   File: server.py View Source Project 5 votes vote down vote up
def __init__(self, connection):
        connection.setblocking(0)
        #//fcntl.fcntl(connection.fileno(), fcntl.F_SETFD, os.O_NONBLOCK)
        # somehow it's much slower to baseclass ?!?
        #super(LineBufferedNonBlockingSocket, self).__init__(connection.fileno())
        self.b = linebuffer.LineBuffer(connection.fileno())

        self.socket = connection
        self.out_buffer = ''
        self.pollout = select.poll()
        self.pollout.register(connection, select.POLLOUT)
        self.sendfail_msg = self.sendfail_cnt = 0 
Example 39
Project: pykit   Author: baishancloud   File: daemonize.py View Source Project 5 votes vote down vote up
def trylock_or_exit(self, timeout=10):

        interval = 0.1
        n = int(timeout / interval) + 1
        flag = fcntl.LOCK_EX | fcntl.LOCK_NB

        for ii in range(n):

            fd = os.open(self.lockfile, os.O_RDWR | os.O_CREAT)

            fcntl.fcntl(fd, fcntl.F_SETFD,
                        fcntl.fcntl(fd, fcntl.F_GETFD, 0)
                        | fcntl.FD_CLOEXEC)

            try:
                fcntl.lockf(fd, flag)

                self.lockfp = os.fdopen(fd, 'w+r')
                break

            except IOError as e:
                os.close(fd)
                if e[0] == errno.EAGAIN:
                    time.sleep(interval)
                else:
                    raise

        else:
            logger.info("Failure acquiring lock %s" % (self.lockfile, ))
            sys.exit(1)

        logger.info("OK acquired lock %s" % (self.lockfile)) 
Example 40
Project: pykit   Author: baishancloud   File: daemonize.py View Source Project 5 votes vote down vote up
def unlock(self):

        if self.lockfp is None:
            return

        fd = self.lockfp.fileno()
        fcntl.lockf(fd, fcntl.LOCK_UN)
        self.lockfp.close()
        self.lockfp = None 
Example 41
Project: py-enarksh   Author: SetBased   File: EventQueueEmptyEventHandler.py View Source Project 5 votes vote down vote up
def init(cls):
        """
        Creates a pipe for waking up a select call when a signal has been received.
        """
        cls.__wake_up_pipe = os.pipe()
        fcntl.fcntl(cls.__wake_up_pipe[0], fcntl.F_SETFL, os.O_NONBLOCK)

        signal.set_wakeup_fd(EventQueueEmptyEventHandler.__wake_up_pipe[1])

    # ------------------------------------------------------------------------------------------------------------------ 
Example 42
Project: zanph   Author: zanph   File: posix.py View Source Project 5 votes vote down vote up
def set_close_exec(fd):
    flags = fcntl.fcntl(fd, fcntl.F_GETFD)
    fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC) 
Example 43
Project: zanph   Author: zanph   File: posix.py View Source Project 5 votes vote down vote up
def _set_nonblocking(fd):
    flags = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) 
Example 44
Project: hostapd-mana   Author: adde88   File: tcp.py View Source Project 5 votes vote down vote up
def createInternetSocket(self):
        """(internal) Create a non-blocking socket using
        self.addressFamily, self.socketType.
        """
        s = socket.socket(self.addressFamily, self.socketType)
        s.setblocking(0)
        if fcntl and hasattr(fcntl, 'FD_CLOEXEC'):
            old = fcntl.fcntl(s.fileno(), fcntl.F_GETFD)
            fcntl.fcntl(s.fileno(), fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
        return s 
Example 45
Project: hostapd-mana   Author: adde88   File: fdesc.py View Source Project 5 votes vote down vote up
def setNonBlocking(fd):
    """Make a fd non-blocking."""
    flags = fcntl.fcntl(fd, FCNTL.F_GETFL)
    flags = flags | os.O_NONBLOCK
    fcntl.fcntl(fd, FCNTL.F_SETFL, flags) 
Example 46
Project: hostapd-mana   Author: adde88   File: fdesc.py View Source Project 5 votes vote down vote up
def setBlocking(fd):
    """Make a fd blocking."""
    flags = fcntl.fcntl(fd, FCNTL.F_GETFL)
    flags = flags & ~os.O_NONBLOCK
    fcntl.fcntl(fd, FCNTL.F_SETFL, flags) 
Example 47
Project: hostapd-mana   Author: adde88   File: base.py View Source Project 5 votes vote down vote up
def createInternetSocket(self):
        s = socket.socket(self.addressFamily, self.socketType)
        s.setblocking(0)
        if fcntl and hasattr(fcntl, 'FD_CLOEXEC'):
            old = fcntl.fcntl(s.fileno(), fcntl.F_GETFD)
            fcntl.fcntl(s.fileno(), fcntl.F_SETFD, old | fcntl.FD_CLOEXEC)
        return s 
Example 48
Project: hostapd-mana   Author: adde88   File: subprocess.py View Source Project 5 votes vote down vote up
def _set_cloexec_flag(self, fd, cloexec=True):
            try:
                cloexec_flag = fcntl.FD_CLOEXEC
            except AttributeError:
                cloexec_flag = 1

            old = fcntl.fcntl(fd, fcntl.F_GETFD)
            if cloexec:
                fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
            else:
                fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag) 
Example 49
Project: hostapd-mana   Author: adde88   File: SimpleXMLRPCServer.py View Source Project 5 votes vote down vote up
def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler,
                 logRequests=True, allow_none=False, encoding=None, bind_and_activate=True):
        self.logRequests = logRequests

        SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding)
        SocketServer.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)

        # [Bug #1222790] If possible, set close-on-exec flag; if a
        # method spawns a subprocess, the subprocess shouldn't have
        # the listening socket open.
        if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
            flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
            flags |= fcntl.FD_CLOEXEC
            fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags) 
Example 50
Project: hostapd-mana   Author: adde88   File: tempfile.py View Source Project 5 votes vote down vote up
def _set_cloexec(fd):
        try:
            flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0)
        except IOError:
            pass
        else:
            # flags read successfully, modify
            flags |= _fcntl.FD_CLOEXEC
            _fcntl.fcntl(fd, _fcntl.F_SETFD, flags)