Esempio n. 1
0
    def do_acquire(self, waitflag=False):
        locked = False

        if waitflag:
            blockflag = 0
        else:
            blockflag = fcntl.LOCK_NB

        self.fd = posix.open(self.fn, O_CREAT | O_RDWR, 0600)
        try:
            fcntl.flock(self.fd, fcntl.LOCK_EX | blockflag)
            # locked it
            try:
                posix.ftruncate(self.fd, 0)
                posix.write(self.fd, ` os.getpid() ` + '\n')
                locked = True
            except:
                self.do_release()
                raise
        except IOError, x:
            if x.errno == errno.EWOULDBLOCK:
                # failed to lock
                posix.close(self.fd)
                del self.fd
            else:
                raise
Esempio n. 2
0
def __import__(filename, module_name):
    import sys, _imp, posix
    module = sys.modules[module_name]
    if filename.startswith("%s"):
        full_filename = filename % __graalpython__.core_home
        filename = filename[len("%s"):]
    elif filename.startswith(__graalpython__.stdlib_home):
        full_filename = filename
        filename = filename[len(__graalpython__.stdlib_home):]
    else:
        raise RuntimeError(
            "There was an import during bootstrap outside the core or stdlib home."
        )

    # If we can, avoid opening the file and use our cached code
    if not __graalpython__.has_cached_code(filename):
        fd = posix.open(full_filename, posix.O_RDONLY)
        content = posix.read(fd, sys.maxsize)
        posix.close(fd)
        code = compile(content, filename, "exec")
    else:
        # n.b.: for these builtin modules, there's never a full path and none of
        # them can be packages
        code = __graalpython__.get_cached_code(filename)

    exec(code, module.__dict__)
    return module
Esempio n. 3
0
    def readSensor(self):
        fd = posix.open("/dev/i2c-%d" % self._i2cbus, posix.O_RDWR)

        ioctl(fd, self.I2C_SLAVE, self.I2C_ADDR)

        # wake AM2320 up, goes to sleep to not warm up and affect the humidity sensor
        # This write will fail as AM2320 won't ACK this write
        try:
            posix.write(fd, b'\0x00')
        except:
            pass
        time.sleep(0.001)  #Wait at least 0.8ms, at most 3ms

        # write at addr 0x03, start reg = 0x00, num regs = 0x04 */
        try:
            posix.write(fd, b'\x03\x00\x04')
        except:
            posix.close(fd)
            return (0, 0, 1, "Device did not acknowledge request")
        time.sleep(0.0016)  #Wait at least 1.5ms for result

        # Read out 8 bytes of result data
        # Byte 0: Should be Modbus function code 0x03
        # Byte 1: Should be number of registers to read (0x04)
        # Byte 2: Humidity msb
        # Byte 3: Humidity lsb
        # Byte 4: Temperature msb
        # Byte 5: Temperature lsb
        # Byte 6: CRC lsb byte
        # Byte 7: CRC msb byte
        data = bytearray(posix.read(fd, 8))
        posix.close(fd)

        # Check data[0] and data[1]
        if data[0] != 0x03 or data[1] != 0x04:
            return (0, 0, 4, "First two read bytes are a mismatch")
        # raise Exception("First two read bytes are a mismatch")

        # CRC check
        if self._calc_crc16(data[0:6]) != self._combine_bytes(
                data[7], data[6]):
            return (0, 0, 4, "CRC failed")
        #  raise Exception("CRC failed")

        # Temperature resolution is 16Bit,
        # temperature highest bit (Bit15) is equal to 1 indicates a
        # negative temperature, the temperature highest bit (Bit15)
        # is equal to 0 indicates a positive temperature;
        # temperature in addition to the most significant bit (Bit14 ~ Bit0)
        # indicates the temperature sensor string value.
        # Temperature sensor value is a string of 10 times the
        # actual temperature value.
        temp = self._combine_bytes(data[4], data[5])
        if temp & 0x8000:
            temp = -(temp & 0x7FFF)
        temp /= 10.0

        humi = self._combine_bytes(data[2], data[3]) / 10.0

        return (temp, humi, 0, '')
Esempio n. 4
0
 def test_ignore_ioerror_in_readall_if_nonempty_result(self):
     # this is the behavior of regular files in CPython 2.7, as
     # well as of _io.FileIO at least in CPython 3.3.  This is
     # *not* the behavior of _io.FileIO in CPython 3.4 or 3.5;
     # see CPython's issue #21090.
     import sys
     try:
         from posix import openpty, fdopen, write, close
     except ImportError:
         skip('no openpty on this platform')
     if 'gnukfreebsd' in sys.platform:
         skip('close() hangs forever on kFreeBSD')
     read_fd, write_fd = openpty()
     write(write_fd, 'Abc\n')
     close(write_fd)
     f = fdopen(read_fd)
     # behavior on Linux: f.read() returns 'Abc\r\n', then the next time
     # it raises IOError.  Behavior on OS/X (Python 2.7.5): the close()
     # above threw away the buffer, and f.read() always returns ''.
     if sys.platform.startswith('linux'):
         s = f.read()
         assert s == 'Abc\r\n'
         raises(IOError, f.read)
     else:
         s = f.read()
         assert s == ''
         s = f.read()
         assert s == ''
     f.close()
Esempio n. 5
0
 def test_ignore_ioerror_in_readall_if_nonempty_result(self):
     # this is the behavior of regular files in CPython 2.7, as
     # well as of _io.FileIO at least in CPython 3.3.  This is
     # *not* the behavior of _io.FileIO in CPython 3.4 or 3.5;
     # see CPython's issue #21090.
     import sys
     try:
         from posix import openpty, fdopen, write, close
     except ImportError:
         skip('no openpty on this platform')
     read_fd, write_fd = openpty()
     write(write_fd, 'Abc\n')
     close(write_fd)
     f = fdopen(read_fd)
     # behavior on Linux: f.read() returns 'Abc\r\n', then the next time
     # it raises IOError.  Behavior on OS/X (Python 2.7.5): the close()
     # above threw away the buffer, and f.read() always returns ''.
     if sys.platform.startswith('linux'):
         s = f.read()
         assert s == 'Abc\r\n'
         raises(IOError, f.read)
     else:
         s = f.read()
         assert s == ''
         s = f.read()
         assert s == ''
     f.close()
def check_module_inspection():
    this_module = __nemesys__.get_module(__name__)

    phase = __nemesys__.module_phase(__name__)
    compiled_size = __nemesys__.module_compiled_size(__name__)
    global_count = __nemesys__.module_global_count(__name__)
    source = __nemesys__.module_source(__name__)

    # these functions should also work if passed the module object
    assert phase == __nemesys__.module_phase(this_module)
    assert compiled_size == __nemesys__.module_compiled_size(this_module)
    assert global_count == __nemesys__.module_global_count(this_module)
    assert source == __nemesys__.module_source(this_module)

    assert phase == "Analyzed"  # doesn't become Imported until the root scope returns
    assert compiled_size > 0
    assert global_count == 8
    # note: the globals are __doc__, __name__, __nemesys__, posix, and the four functions

    assert b'this string appears verbatim in the module source' in source
    assert b'this string does not appear verbatim because it has an escaped\x20character' not in source

    # read the contents of this file and make sure it matches module_source
    fd = posix.open(__file__, posix.O_RDONLY)
    data = posix.read(fd, 2 * len(source))
    posix.close(fd)
    assert data == source, '%s != %s' % (repr(data), repr(source))
Esempio n. 7
0
 def do_release(self):
     if self.fd is not None:
         posix.ftruncate(self.fd, 0)
         fcntl.flock(self.fd, fcntl.LOCK_UN)
         posix.close(self.fd)
         self.fd = None
         self._locked = False
Esempio n. 8
0
    def Pop(self):
        frame = self.stack.pop()
        #log('< Pop %s', frame)
        for saved, orig in reversed(frame.saved):
            try:
                posix.dup2(saved, orig)
            except OSError as e:
                log('dup2(%d, %d) error: %s', saved, orig, e)
                #log('fd state:')
                #posix.system('ls -l /proc/%s/fd' % posix.getpid())
                raise
            posix.close(saved)
            #log('dup2 %s %s', saved, orig)

        for fd in frame.need_close:
            #log('Close %d', fd)
            try:
                posix.close(fd)
            except OSError as e:
                log('Error closing descriptor %d: %s', fd, e)
                raise

        # Wait for here doc processes to finish.
        for proc, waiter in frame.need_wait:
            unused_status = proc.WaitUntilDone(waiter)
Esempio n. 9
0
 def do_release(self):
     if self.fd is not None:
         posix.ftruncate(self.fd, 0)
         fcntl.flock(self.fd, fcntl.LOCK_UN)
         posix.close(self.fd)
         self.fd = None
         self._locked = False
Esempio n. 10
0
    def Pop(self):
        frame = self.stack.pop()
        #log('< Pop %s', frame)
        for saved, orig in reversed(frame.saved):
            try:
                posix.dup2(saved, orig)
            except OSError as e:
                log('dup2(%d, %d) error: %s', saved, orig, e)
                #log('fd state:')
                #posix.system('ls -l /proc/%s/fd' % posix.getpid())
                raise
            posix.close(saved)
            #log('dup2 %s %s', saved, orig)

            # NOTE: This balances the increments from _PushDup().  But it doesn't
            # balance the ones from Open().
            self.next_fd -= 1  # Count down
            assert self.next_fd >= 10, self.next_fd

        for fd in frame.need_close:
            #log('Close %d', fd)
            try:
                posix.close(fd)
            except OSError as e:
                log('Error closing descriptor %d: %s', fd, e)
                raise

        # Wait for here doc processes to finish.
        for proc, waiter in frame.need_wait:
            unused_status = proc.WaitUntilDone(waiter)
Esempio n. 11
0
    def Open(self, path, mode='r'):
        """Opens a path for read, but moves it out of the reserved 3-9 fd range.

    Returns:
      A Python file object.  The caller is responsible for Close().

    Raises:
      OSError if the path can't be found.
    """
        if mode == 'r':
            fd_mode = posix.O_RDONLY
        elif mode == 'w':
            fd_mode = posix.O_CREAT | posix.O_RDWR
        else:
            raise AssertionError(mode)

        fd = posix.open(path, fd_mode, 0666)  # may raise OSError
        new_fd = self._GetFreeDescriptor()
        posix.dup2(fd, new_fd)
        posix.close(fd)
        try:
            f = posix.fdopen(new_fd, mode)  # Might raise IOError
        except IOError as e:
            raise OSError(*e.args)  # Consistently raise OSError
        return f
Esempio n. 12
0
    def Run(self, waiter, fd_state):
        """Run this pipeline synchronously."""
        self.Start(waiter)

        # Run our portion IN PARALLEL with other processes.  This may or may not
        # fork:
        # ls | wc -l
        # echo foo | read line  # no need to fork

        ex, node = self.last_thunk

        #log('thunk %s', self.last_thunk)
        if self.last_pipe is not None:
            r, w = self.last_pipe  # set in AddLast()
            posix.close(w)  # we will not write here
            fd_state.PushStdinFromPipe(r)
            try:
                ex.ExecuteAndCatch(node)
            finally:
                fd_state.Pop()
        else:
            ex.ExecuteAndCatch(node)

        self.pipe_status[-1] = ex.LastStatus()
        #log('pipestatus before all have finished = %s', self.pipe_status)

        return self.WaitUntilDone(waiter)  # returns pipe_status
Esempio n. 13
0
    def read_sensor(self):
        fd = posix.open('/dev/i2c-%d' % self._i2cbus, posix.O_RDWR)
        ioctl(fd, I2C_SLAVE, self.I2C_ADDR)
        try:
            posix.write(fd, b'\0x00')  # wake up AM2320
        except:
            pass
        time.sleep(0.01)
        posix.write(
            fd, b'\x03\x00\x04'
        )  # x03(function code) x00(starting address) x04(register length)
        time.sleep(0.002)
        data = bytearray(posix.read(fd, 8))
        posix.close(fd)

        if data[0] != 0x03 or data[
                1] != 0x04:  # Modbus function code (0x03), number of registers to read (0x04)
            raise Exception('I2C read failure')
        if self._calc_crc16(data[0:6]) != self._combine_bytes(
                data[7], data[6]):
            raise Exception('CRC failure')

        humi = self._combine_bytes(data[2], data[3]) / 10.0
        temp = self._combine_bytes(data[4], data[5])
        if temp & 0x8000:
            temp = -(temp & 0x7FFF)
        temp /= 10.0
        return (temp, humi)
Esempio n. 14
0
        def do_acquire(self, waitflag=False):
            locked = False

            if waitflag:
                blockflag = 0
            else:
                blockflag = fcntl.LOCK_NB

            self.fd = posix.open(self.fn, O_CREAT | O_RDWR, 0600)
            try:
                fcntl.flock(self.fd, fcntl.LOCK_EX|blockflag)
                # locked it
                try:
                    posix.ftruncate(self.fd, 0)
                    posix.write(self.fd, `os.getpid()` + '\n')
                    locked = True
                except:
                    self.do_release()
                    raise
            except IOError, x:
                if x.errno == errno.EWOULDBLOCK:
                    # failed to lock
                    posix.close(self.fd)
                    del self.fd
                else:
                    raise
Esempio n. 15
0
    def start(self):
        if self._monitoring:
            if self._mode == MonitorService.MODE_FIFO:
                # publish fifo
                self._tmpdir = tempfile.mkdtemp()
                self._filename = os.path.join(self._tmpdir, 'siis.stream')

                try:
                    os.mkfifo(self._filename, 0o600)
                except OSError as e:
                    logger.error("Failed to create monitor write FIFO: %s" % repr(e))
                    os.rmdir(self._tmpdir)
                    self._filename = None
                else:
                    self._fifo = posix.open(self._filename, posix.O_NONBLOCK | posix.O_RDWR)  # posix.O_WRONLY

                # read command fifo
                self._filename_read = os.path.join(self._tmpdir, 'siis.rpc')

                try:
                    os.mkfifo(self._filename_read, 0o600)
                except OSError as e:
                    logger.error("Failed to create monitor read FIFO: %s" % repr(e))
                    os.rmdir(self._tmpdir)

                    # close the write fifo
                    os.remove(self._filename)
                    posix.close(self._fifo)
                    self._fifo = -1
                    self._filename = None
                    self._filename_read = None
                else:
                    self._fifo_read = posix.open(self._filename_read, posix.O_NONBLOCK)

                if self._fifo and self._fifo_read:
                    self._running = True
                    self._thread = threading.Thread(name="monitor", target=self.run_fifo)
                    self._thread.start()

            elif self._mode == MonitorService.MODE_HTTP_WEBSOCKET:
                # logger.startLogging(sys.stdout)

                self._factory = WebSocketServerFactory(u"ws://%s:%i" % (self._host, self._port))
                self._factory.protocol = ServerProtocol
                # self._factory.setProtocolOptions(maxConnections=2)

                # self._loop = asyncio.get_event_loop()
                # coro = self._loop.create_server(self._factory, self._host, self._port)
                # self._server = self._loop.run_until_complete(coro)

                # reactor.listenTCP(self._port, self._factory)
                # if not reactor.running:
                #     reactor.run()

                self._running = True
                self._thread = threading.Thread(name="monitor", target=self.run_autobahn)
                self._thread.start()
Esempio n. 16
0
    def terminate(self):
        # remove any streamables
        self._running = False

        if self._mode == MonitorService.MODE_FIFO:
            if self._thread:
                try:
                    self._thread.join()
                except:
                    pass

                self._thread = None

            if self._fifo_read:
                try:
                    posix.close(self._fifo_read)
                    self._fifo_read = -1
                except (BrokenPipeError, IOError):
                    pass

                if self._filename_read:
                    os.remove(self._filename_read)
                    self._filename_read = None

            if self._fifo:
                try:
                    posix.close(self._fifo)
                    self._fifo = -1
                except (BrokenPipeError, IOError):
                    pass

                if self._filename:
                    os.remove(self._filename)
                    self._filename = None

            if self._tmpdir:
                os.rmdir(self._tmpdir)
                self._tmpdir = None

        elif self._mode == MonitorService.MODE_HTTP_WEBSOCKET:
            if self._loop:
                self._loop.stop()

            if self._thread:
                try:
                    self._thread.join()
                except:
                    pass

                self._thread = None

            if self._server:
                self._server.close()
                self._loop.close()

            self._server = None
            self._loop = None
Esempio n. 17
0
def __import__(filename, module_name):
    import sys, posix
    module = sys.modules[module_name]
    if filename.startswith("%s"):
        filename = filename % sys.graal_python_core_home
    fd = posix.open(filename, posix.O_RDONLY)
    content = posix.read(fd, sys.maxsize)
    posix.close(fd)
    code = compile(content, filename, "exec")
    eval(code, module.__dict__)
    return module
Esempio n. 18
0
    def Run(self):
        """
    do_exit: For small pipelines
    """
        #log('Writing %r', self.body_str)
        posix.write(self.w, self.body_str)
        #log('Wrote %r', self.body_str)
        posix.close(self.w)
        #log('Closed %d', self.w)

        sys.exit(0)  # Could this fail?
Esempio n. 19
0
def execute_command():
    pipe_fd = posix.pipe()
    pid = posix.fork()
    if pid == 0:
        cmdline = ["lsblk"]
        if check_fs_val.get() or check_UUID_val.get():
            cmdline.append("-o")
            col = "+"
            if check_fs_val.get():
                col += "fstype"
            if check_fs_val.get() and check_UUID_val.get():
                col += ","
            if check_UUID_val.get():
                col += "UUID"
            cmdline.append(col)
        posix.dup2(pipe_fd[1], 1)
        posix.close(pipe_fd[0])
        posix.close(pipe_fd[1])
        posix.execv("/bin/lsblk", cmdline)
        quit()
    else:
        posix.close(pipe_fd[1])
        ret = bytearray()
        readbytes = posix.read(pipe_fd[0], 1000)
        while readbytes != b"":
            ret += readbytes
            readbytes = posix.read(pipe_fd[0], 1000)
        posix.close(pipe_fd[0])
        posix.wait()
        return str(ret, sys.stdout.encoding)
Esempio n. 20
0
    def test_pass_fds_make_inheritable(self):
        import subprocess, posix

        fd1, fd2 = posix.pipe()
        assert posix.get_inheritable(fd1) is False
        assert posix.get_inheritable(fd2) is False

        subprocess.check_call(['/usr/bin/env', 'python', '-c',
                               'import os;os.write(%d,b"K")' % fd2],
                              close_fds=True, pass_fds=[fd2])
        res = posix.read(fd1, 1)
        assert res == b"K"
        posix.close(fd1)
        posix.close(fd2)
Esempio n. 21
0
 def test_rename_at_close_correct_read(self):
     firstFileFd = posix.open("mount/file1", posix.O_RDONLY)
     secondFileFd = posix.open("mount/file2", posix.O_RDONLY)
     for i in range(1000):
         position = random.randint(0, 10000)
         size = random.randint(1, 10000)
         posix.lseek(firstFileFd,position, 0)
         posix.lseek(secondFileFd, position, 0)
         posix.read(firstFileFd, size)
         posix.read(secondFileFd, size)
     posix.close(firstFileFd)
     posix.close(secondFileFd)
     posix.rename("mount/file2", "mount/file3")
     posix.rename("mount/file1","mount/file2")
     self.assertTrue(open("mount/file2").read()== open("src/file2").read())
Esempio n. 22
0
 def one_loop(self):
     ret = True
     for (fd, ev) in self.poller.poll(1000):
         if ev & (select.POLLERR | select.POLLHUP):
             self.flush_outputs()
             self.poller.unregister(fd)
             ret = False
         if ev & select.POLLIN:
             data = posix.read(fd, 4096)
             if not data:
                 posix.close(self.fd_map[fd])
                 ret = False
             self.queue_write(self.fd_map[fd], data)
         if ev & select.POLLOUT:
             self.do_write(fd)
     return ret
Esempio n. 23
0
 def one_loop(self):
     ret = True
     for (fd, ev) in self.poller.poll(1000):
         if ev & (select.POLLERR | select.POLLHUP):
             self.flush_outputs()
             self.poller.unregister(fd)
             ret = False
         if ev & select.POLLIN:
             data = posix.read(fd, 4096)
             if not data:
                 posix.close(self.fd_map[fd])
                 ret = False
             self.queue_write(self.fd_map[fd], data)
         if ev & select.POLLOUT:
             self.do_write(fd)
     return ret
Esempio n. 24
0
 def test_ignore_ioerror_in_readall_if_nonempty_result(self):
     # this is the behavior of regular files in CPython 2.7, as
     # well as of _io.FileIO at least in CPython 3.3.  This is
     # *not* the behavior of _io.FileIO in CPython 3.4 or 3.5;
     # see CPython's issue #21090.
     try:
         from posix import openpty, fdopen, write, close
     except ImportError:
         skip('no openpty on this platform')
     read_fd, write_fd = openpty()
     write(write_fd, 'Abc\n')
     close(write_fd)
     f = fdopen(read_fd)
     s = f.read()
     assert s == 'Abc\r\n'
     raises(IOError, f.read)
     f.close()
Esempio n. 25
0
    def make_tempfile(fn, pid):
        tfn = os.path.join(os.path.dirname(fn), 'shlock%d.tmp' % pid)

        errcount = 1000
        while 1:
            try:
                fd = posix.open(tfn, O_EXCL | O_CREAT | O_RDWR, 0600)
                posix.write(fd, '%d\n' % pid)
                posix.close(fd)

                return tfn
            except OSError, x:
                if (errcount > 0) and (x.errno == errno.EEXIST):
                    os.unlink(tfn)
                    errcount = errcount - 1
                else:
                    raise
Esempio n. 26
0
 def test_ignore_ioerror_in_readall_if_nonempty_result(self):
     # this is the behavior of regular files in CPython 2.7, as
     # well as of _io.FileIO at least in CPython 3.3.  This is
     # *not* the behavior of _io.FileIO in CPython 3.4 or 3.5;
     # see CPython's issue #21090.
     try:
         from posix import openpty, fdopen, write, close
     except ImportError:
         skip('no openpty on this platform')
     read_fd, write_fd = openpty()
     write(write_fd, 'Abc\n')
     close(write_fd)
     f = fdopen(read_fd)
     s = f.read()
     assert s == 'Abc\r\n'
     raises(IOError, f.read)
     f.close()
Esempio n. 27
0
    def make_tempfile(fn, pid):
        tfn = os.path.join(os.path.dirname(fn), 'shlock%d.tmp' % pid)

        errcount = 1000
        while 1:
            try:
                fd = posix.open(tfn, O_EXCL | O_CREAT | O_RDWR, 0600)
                posix.write(fd, '%d\n' % pid)
                posix.close(fd)

                return tfn
            except OSError, x:
                if (errcount > 0) and (x.errno == errno.EEXIST):
                    os.unlink(tfn)
                    errcount = errcount - 1
                else:
                    raise
Esempio n. 28
0
def jog_i2c_write(addr, register, value, debug):
    import fcntl
    import posix

    n_i2c = 0
    f_i2c = posix.open("/dev/i2c-%i" % n_i2c, posix.O_RDWR)

    flags = I2C_M_WR
    buf = ctypes.create_string_buffer(2)
    buf[0] = chr(register)
    buf[1] = chr(value)
    msgs = I2cMsg(addr=addr, flags=flags, len=ctypes.sizeof(buf), buf=buf)
    msg_array, msg_count = i2c_ioctl_msg(msgs)
    io_i2c = I2cRdwrIoctlData(msgs=msg_array, nmsgs=msg_count)
    i2c_stat = fcntl.ioctl(f_i2c, I2C_RDWR, io_i2c)

    posix.close(f_i2c)
Esempio n. 29
0
 async def _read(self):
     while True:
         if self.fd != -1:
             try:
                 res = posix.read(self.fd, 1)
                 size = len(res)
             except:
                 self._timer -= 1
                 if self._timer < 0:
                     error = sys.exc_info()[1]
                     async with self._fdcond:
                         posix.close(self.fd)
                         self.fd = -1
                         self._timer = self.timeout_ms
                         logger.debug(f"BLE: Disconnected {error}")
                         self._fdcond.notify_all()
             else:
                 self._timer = self.timeout_ms
         await asyncio.sleep(1 / 1000)
Esempio n. 30
0
  def RunCommandSub(self, node):
    p = self._MakeProcess(node,
                          disable_errexit=not self.exec_opts.strict_errexit)

    r, w = posix.pipe()
    p.AddStateChange(process.StdoutToPipe(r, w))
    pid = p.Start()
    #log('Command sub started %d', pid)
    self.waiter.Register(pid, p.WhenDone)

    chunks = []
    posix.close(w)  # not going to write
    while True:
      byte_str = posix.read(r, 4096)
      if not byte_str:
        break
      chunks.append(byte_str)
    posix.close(r)

    status = p.WaitUntilDone(self.waiter)

    # OSH has the concept of aborting in the middle of a WORD.  We're not
    # waiting until the command is over!
    if self.exec_opts.strict_errexit:
      if self.exec_opts.ErrExit() and status != 0:
        raise util.ErrExitFailure(
            'Command sub exited with status %d (%r)', status,
            node.__class__.__name__)
    else:
      # Set a flag so we check errexit at the same time as bash.  Example:
      #
      # a=$(false)
      # echo foo  # no matter what comes here, the flag is reset
      #
      # Set ONLY until this command node has finished executing.
      self.check_command_sub_status = True
      self.mem.last_status = status

    # Runtime errors test case: # $("echo foo > $@")
    # Why rstrip()?
    # https://unix.stackexchange.com/questions/17747/why-does-shell-command-substitution-gobble-up-a-trailing-newline-char
    return ''.join(chunks).rstrip('\n')
Esempio n. 31
0
    def _PushDup(self, fd1, fd2):
        """Save fd2, and dup fd1 onto fd2.

    Mutates self.cur_frame.saved.

    Returns:
      success Bool
    """
        new_fd = self._NextFreeFileDescriptor()
        #log('---- _PushDup %s %s', fd1, fd2)
        need_restore = True
        try:
            #log('DUPFD %s %s', fd2, self.next_fd)
            fcntl.fcntl(fd2, fcntl.F_DUPFD, new_fd)
        except IOError as e:
            # Example program that causes this error: exec 4>&1.  Descriptor 4 isn't
            # open.
            # This seems to be ignored in dash too in savefd()?
            if e.errno == errno.EBADF:
                #log('ERROR %s', e)
                need_restore = False
            else:
                raise
        else:
            posix.close(fd2)
            fcntl.fcntl(new_fd, fcntl.F_SETFD, fcntl.FD_CLOEXEC)

        #log('==== dup %s %s\n' % (fd1, fd2))
        try:
            posix.dup2(fd1, fd2)
        except OSError as e:
            # bash/dash give this error too, e.g. for 'echo hi 1>&3'
            util.error('%d: %s', fd1, posix.strerror(e.errno))
            # Restore and return error
            posix.dup2(new_fd, fd2)
            posix.close(new_fd)
            # Undo it
            return False

        if need_restore:
            self.cur_frame.saved.append((new_fd, fd2))
        return True
Esempio n. 32
0
    def Open(self, path, mode='r'):
        """Opens a path for read, but moves it out of the reserved 3-9 fd range.

    Returns:
      A Python file object.  The caller is responsible for Close().

    Raises:
      OSError if the path can't be found.
    """
        if mode == 'r':
            fd_mode = posix.O_RDONLY
        elif mode == 'w':
            fd_mode = posix.O_CREAT | posix.O_RDWR
        else:
            raise AssertionError(mode)

        fd = posix.open(path, fd_mode, 0666)
        new_fd = self._NextFreeFileDescriptor()
        posix.dup2(fd, new_fd)
        posix.close(fd)
        return posix.fdopen(new_fd, mode)
Esempio n. 33
0
    def test_rename_folder_correct_read(self):
        os.mkdir("src/folder1")
        os.mkdir("src/folder2")
        os.system("cp src/file1 src/folder1/file") 
        os.system("cp src/file2 src/folder2/file") 


        firstFileFd = posix.open("mount/folder1/file", posix.O_RDONLY)
        secondFileFd = posix.open("mount/folder2/file", posix.O_RDONLY)
        for i in range(1000):
            position = random.randint(0, 10000)
            size = random.randint(1, 10000)
            posix.lseek(firstFileFd,position, 0)
            posix.lseek(secondFileFd, position, 0)
            posix.read(firstFileFd, size)
            posix.read(secondFileFd, size)
        posix.rename("mount/folder2", "mount/folder3")
        posix.rename("mount/folder1","mount/folder2")
        posix.close(firstFileFd)
        posix.close(secondFileFd)
        self.assertTrue(open("mount/folder2/file").read()== open("src/folder2/file").read())
def main():
    Raise = False
    try:
        fd=posix.open("/dev/serial0", posix.O_RDWR |\
                      posix.O_NOCTTY | posix.O_NDELAY)
    except:
        Raise = True

    if Raise:
        raise Exception("UART busy."
                        " Try /dev/serial1, /dev/ttyS0,"
                        " /dev/ttyAMA0.")

    options = termios.tcgetattr(fd)
    options[0] = termios.IGNPAR
    options[1] = 0
    options[2]=termios.B9600 |\
               termios.CS8 |\
               termios.CLOCAL |\
               termios.CREAD
    options[3] = 0

    termios.tcflush(fd, termios.TCIFLUSH)
    termios.tcsetattr(fd, termios.TCSANOW, options)

    while True:
        try:
            message = input("Producer :")
        except EOFError:
            print("")
            break

        binmess = bytearray(len(message))
        for i in range(len(message)):
            binmess[i] = ord(message[i])

        posix.write(fd, binmess)

    posix.close(fd)
Esempio n. 35
0
 def test_randomAccessToFile(self):
     position = 0
     size = 0
     srcFileFd = posix.open("src/file1", posix.O_RDONLY)
     mountFileFd = posix.open("mount/file1", posix.O_RDONLY)
     for i in range(10000):
         position = random.randint(0, 10000)
         size = random.randint(1, 10000)
         posix.lseek(srcFileFd,position, 0)
         posix.lseek(mountFileFd, position, 0)
         if (posix.read(srcFileFd,size) !=  posix.read(mountFileFd, size)):
             posix.close(srcFileFd)
             posix.close(mountFileFd)
             self.assertTrue(False)
     posix.close(srcFileFd)
     posix.close(mountFileFd)
Esempio n. 36
0
def autostart(reason, **kwargs):
	sys.stderr.write("RunScript %d\n" % reason)
	if reason == 0:
		session = kwargs.get('session')
		sys.stderr.write("RunScript %s\n" % session)
		if session is None:
			return
		try:
			os.mkfifo('/tmp/run_script.fifo', 0o666)
		except OSError:
			pass
		try:
			os.mkfifo('/tmp/run_script_output.fifo', 0o666)
		except OSError:
			pass
		thread = Thread(target=run_server, args=(kwargs.get('session'),))
		thread.start()
	elif reason == 1:
		try:
			fp = posix.open('/tmp/run_script.fifo', posix.O_WRONLY | posix.O_NONBLOCK)
			os.write(fp, 'quit\n')
			posix.close(fp)
		except OSError:
			pass
Esempio n. 37
0
def daemonize(logfile):
    try:
        from os import fork
        from posix import close
    except:
        print 'Daemon mode is not supported on this platform (missing fork() syscall or posix module)'
        sys_exit(-1)

    import sys
    if (fork()): sys_exit(0)  # parent return to shell

    ### Child
    close(sys.stdin.fileno())
    sys.stdin = open('/dev/null')
    close(sys.stdout.fileno())
    sys.stdout = Log(open(logfile, 'a+'))
    close(sys.stderr.fileno())
    sys.stderr = Log(open(logfile, 'a+'))
    chdir('/')
Esempio n. 38
0
def daemonize(logfile):
    try:
        from os import fork
        from posix import close
    except:
        print 'Daemon mode is not supported on this platform (missing fork() syscall or posix module)'
        sys_exit(-1)

    import sys
    if (fork()): sys_exit(0) # parent return to shell

    ### Child
    close(sys.stdin.fileno())
    sys.stdin  = open('/dev/null')
    close(sys.stdout.fileno())
    sys.stdout = Log(open(logfile, 'a+'))
    close(sys.stderr.fileno())
    sys.stderr = Log(open(logfile, 'a+'))
    chdir('/')
Esempio n. 39
0
 def close(self):
     """
     Closes the I2C bus device.
     """
     posix.close(self.fd)
Esempio n. 40
0
 def close(self):
     posix.close(self.fd)
Esempio n. 41
0
 def close_fd(self):
     posix.close(self.fd)
     del self.fd
Esempio n. 42
0
 def Close(self):
     """ Close the filehandle to this bus """ 
     posix.close(self.File)
Esempio n. 43
0
def deinit():
    """Closes the SPI device file descriptor."""
    global spidev_fd
    if spidev_fd:
        posix.close(spidev_fd)
    spidev_fd = None
Esempio n. 44
0
 def test_dont_close_fd_if_dir_check_fails_in_fdopen(self):
     import posix
     fd = posix.open('/', posix.O_RDONLY)
     raises(IOError, posix.fdopen, fd)
     posix.close(fd)
 def close(self):
     """Closes the SPI device file descriptor."""
     posix.close(self.fd)
     self.fd = None
Esempio n. 46
0
import fcntl
Esempio n. 47
0
def deinit():
    """Closes the spidev file descriptor"""
    global spidev_fd
    posix.close(spidev_fd)
Esempio n. 48
0
	def close(self):
		dummy = posix.close(self.fd)
Esempio n. 49
0
 def __del__(self):
     try:
         posix.close(self.fd)
     except AttributeError:
         pass #Do nothing in this case.
Esempio n. 50
0
 def close(self):
     """
     Closes the file descriptor.
     """
     posix.close(self.fd)
Esempio n. 51
0
 def close_fd(self):
     posix.close(self.fd)
     self.fd = None