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 SendPacket(self, packet):
     packet = scapy.Ether(src=self._routermac, dst=self._mymac) / packet
     try:
         posix.write(self._tun.fileno(), str(packet))
     except Exception, e:
         if not self._stopped:
             raise e
  def SendRA(cls, netid, retranstimer=None, reachabletime=0):
    validity = 300                 # seconds
    macaddr = cls.RouterMacAddress(netid)
    lladdr = cls._RouterAddress(netid, 6)

    if retranstimer is None:
      # If no retrans timer was specified, pick one that's as long as the
      # router lifetime. This ensures that no spurious ND retransmits
      # will interfere with test expectations.
      retranstimer = validity

    # We don't want any routes in the main table. If the kernel doesn't support
    # putting RA routes into per-interface tables, configure routing manually.
    routerlifetime = validity if HAVE_AUTOCONF_TABLE else 0

    ra = (scapy.Ether(src=macaddr, dst="33:33:00:00:00:01") /
          scapy.IPv6(src=lladdr, hlim=255) /
          scapy.ICMPv6ND_RA(reachabletime=reachabletime,
                            retranstimer=retranstimer,
                            routerlifetime=routerlifetime) /
          scapy.ICMPv6NDOptSrcLLAddr(lladdr=macaddr) /
          scapy.ICMPv6NDOptPrefixInfo(prefix=cls.IPv6Prefix(netid),
                                      prefixlen=64,
                                      L=1, A=1,
                                      validlifetime=validity,
                                      preferredlifetime=validity))
    posix.write(cls.tuns[netid].fileno(), str(ra))
Esempio n. 4
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. 5
0
    def SendRA(cls, netid, retranstimer=None, reachabletime=0):
        validity = 300  # seconds
        macaddr = cls.RouterMacAddress(netid)
        lladdr = cls._RouterAddress(netid, 6)

        if retranstimer is None:
            # If no retrans timer was specified, pick one that's as long as the
            # router lifetime. This ensures that no spurious ND retransmits
            # will interfere with test expectations.
            retranstimer = validity

        # We don't want any routes in the main table. If the kernel doesn't support
        # putting RA routes into per-interface tables, configure routing manually.
        routerlifetime = validity if HAVE_AUTOCONF_TABLE else 0

        ra = (scapy.Ether(src=macaddr, dst="33:33:00:00:00:01") /
              scapy.IPv6(src=lladdr, hlim=255) /
              scapy.ICMPv6ND_RA(reachabletime=reachabletime,
                                retranstimer=retranstimer,
                                routerlifetime=routerlifetime) /
              scapy.ICMPv6NDOptSrcLLAddr(lladdr=macaddr) /
              scapy.ICMPv6NDOptPrefixInfo(prefix=cls.IPv6Prefix(netid),
                                          prefixlen=64,
                                          L=1,
                                          A=1,
                                          validlifetime=validity,
                                          preferredlifetime=validity))
        posix.write(cls.tuns[netid].fileno(), str(ra))
Esempio n. 6
0
    def readSensor(self):
        fd = posix.open("/dev/i2c-%d" % self._i2cbus, posix.O_RDWR)

        ioctl(fd, self.I2C_SLAVE, self.I2C_ADDR)
        try:
            posix.write(fd, b'\0x00')
        except:
            pass
        time.sleep(0.001)

        posix.write(fd, b'\x03\x00\x04')
        time.sleep(0.0016)

        data = bytearray(posix.read(fd, 8))

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

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

        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)
Esempio n. 7
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. 8
0
    def run_fifo(self):
        size = 32768
        cur = bytearray()

        while self._running:
            if self._fifo > 0 and self._fifo_read and self._monitoring:
                # receive
                try:
                    # buf = posix.read(self._fifo, len(buf))
                    # buf = os.read(self._fifo, size)
                    buf = os.read(self._fifo_read, size)

                    if buf:
                        for n in buf:
                            if n == 10:  # new line as message termination
                                try:
                                    msg = json.loads(cur.decode('utf8'))
                                    self.on_rpc_message(msg)

                                except Exception as e:
                                    error_logger.error(repr(e))
                                    traceback_logger.error(
                                        traceback.format_exc())

                                cur = bytearray()
                            else:
                                cur.append(n)

                except (BrokenPipeError, IOError):
                    pass

                # publish
                count = 0

                while self._content:
                    c = self._content.popleft()

                    # insert category, group and stream name
                    c[3]['c'] = c[0]
                    c[3]['g'] = c[1]
                    c[3]['s'] = c[2]

                    try:
                        # write to fifo
                        posix.write(self._fifo,
                                    (json.dumps(c[3]) + '\n').encode('utf8'))
                    except (BrokenPipeError, IOError):
                        pass
                    except (TypeError, ValueError) as e:
                        error_logger.error(
                            "Monitor error sending message : %s" % repr(c))
                        traceback_logger.error(traceback.format_exc())

                    count += 1
                    if count > 10:
                        break

            # don't waste the CPU, might need a condition on outgoing data and on select incoming
            # but this will be replaced by an asyncio WS + REST API
            time.sleep(0.001)
Esempio n. 9
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()
Esempio n. 10
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. 11
0
 def _despertar(self, espera):
   # 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(self._fd, b'\0x00')
   except:
     pass	   	#se lanza excepcion al enviarle NULL
   time.sleep(espera)
Esempio n. 12
0
def SetSpeedup(speedup):
    global f
    speedup = float(speedup)
    # Opening the file for reading and writing prevents blocking until a reader opens the file.
    if f is None:
        f = posix.open(FIFO, posix.O_RDWR | posix.O_CREAT)
    posix.ftruncate(f, 0)
    SEEK_SET = 0
    posix.lseek(f, 0, SEEK_SET)
    posix.write(f, struct.pack("f", speedup))
Esempio n. 13
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. 14
0
 def readSensor(self):
         
         fd = posix.open("/dev/i2c-%d" % self._i2cbus, posix.O_RDWR)
         ioctl(fd, self.I2C_SLAVE, self.I2C_ADDR)
         
         # wake up AM2320 sensor, it sleeps when not being
         # called to keep from heating up and effecting temp, humidity
         try:
             posix.write(fd, b'\0x00')
         except:
             pass
         time.sleep(0.001)  # sleep at least 0.8ms
         
         # write at addr 0x03, start register 0x00, n_registers = 0x04
         posix.write(fd, b'\x03\x00\x04')
         time.sleep(0.0016)  # wait for sensor result min 1.5ms
         
         
         # 8 bytes of data
         # 0: modbus function code 0x03
         # 1: n registers to read 0x04
         # 2: humidity msb ( most significate byte )
         # 3: humidity lsb ( least significate byte )
         # 4: temp msb
         # 5: temp lsb
         # 6: CRC lsb
         # 7: CRC msb
         data = bytearray(posix.read(fd, 8))
         
         # check data[0], data[1]
         if data[0] != 0x03 or data[1] != 0x04:
             print("First two bytes mismatch")
             
         #CRC check
         if self._calc_crc16(data[0:6]) != self._combine_bytes(data[7], data[6]):
             pass
                           
         # temp resolution 16bits
         # temp bit 15 == 1 means negative temperature, 0 positive
         # temp in addition to most significant bit Bit14 ~ Bit0
         # indicates string value
         # sensor value is string of 10x actual temp
                           
         temp = self._combine_bytes(data[4], data[5])
         if temp & 0x8000:
             temp = -(temp & 0x7FFF)    # wrap back to positive, and with 32767
         temp /= 10.0
         
         humidity = self._combine_bytes(data[2], data[3]) / 10.0
         
         return (temp, humidity)
Esempio n. 15
0
    def set_registers(self, addresses, data):
        # this is a direct implemetation of the Bosch bme280.c function
        # i colud re write it for sliker memory management
        length = len(data)
        temp = bytearray((2 * length) - 1)
        temp[0] = data[0]

        if length > 1:
            for i in range(1, length):
                temp[(i * 2) - 1] = addresses[i]
                temp[(i * 2)] = data[i]

        buf = bytearray(1)
        buf[0] = addresses[0]
        buf += temp

        posix.write(self._fd, buf)
Esempio n. 16
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. 17
0
    def __getitem__(self, key):
        addr = struct.pack('B', key)
        if posix.write(self.fd, addr) != 1:
            raise Exception()

        ret_val = struct.unpack('B', posix.read(self.fd, 1))[0]

        return ret_val
Esempio n. 18
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. 19
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. 20
0
    def __getitem__(self, key):
        addr = struct.pack('B', key)
        if posix.write(self.fd, addr) != 1:
            raise Exception()

        ret_val = struct.unpack('B', posix.read(self.fd, 1))[0]

        return ret_val
Esempio n. 21
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. 22
0
  def leerTemHume(self):
    self._despertar(0.008)
      
    # write command 0x03, start reg = 0x00, num regs = 0x04
    posix.write(self._fd, b'\x03\x00\x04')
    #Wait at least 1.5ms for result
    time.sleep(0.0016) 

    # 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(self._fd, 8))
  
    # Check data[0] and data[1] if not correct throw Exception
    if data[0] != 0x03 or data[1] != 0x04:
      raise Exception("First two bytes not as expected")

    # CRC check
    if self._calc_crc16(data[0:6]) != self._combine_bytes(data[7], data[6]):
      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)
Esempio n. 23
0
    def read(self, addr, _len):
        if isinstance(addr, EnumMeta) and hasattr(addr, "ADDR"):
            addr = addr.ADDR.value
        elif isinstance(addr, Enum):
            addr = addr.value

        addr = struct.pack('B', addr)
        if posix.write(self.fd, addr) != 1:
            raise Exception()

        return posix.read(self.fd, _len)
Esempio n. 24
0
    def read_keys(self, pin):
        posix.write(self._fd, b'\x00')
        keys = bytearray(posix.read(self._fd, 2))
        keycode = (keys[1] & 0x1f) << 8 | keys[0]

        # keys 0 to 9 and # & *
        for i in range(12):
            mask = 0x01 << i

            if mask & keycode:
                self._pads[i]._touch()
            else:
                self._pads[i]._release()

        # proximity
        mask = 0x01 << 12

        if mask & keycode:
            self.keypad._close_by()
        else:
            self.keypad._far_away()
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. 26
0
    def do_write(self, outfd):
        if not self.out_buf[outfd]:
            return

        (rl, wl, el) = select.select([], [outfd], [outfd])
        if outfd in wl:
            length = posix.write(outfd, self.out_buf[outfd])
            self.out_buf[outfd] = self.out_buf[outfd][length:]
            if not self.out_buf[outfd]:
                self.select_for_read(outfd)
                del self.out_buf[outfd]
        elif fd in el:
            raise Exception('could not flush fd')
Esempio n. 27
0
    def do_write(self, outfd):
        if not self.out_buf[outfd]:
            return

        (rl, wl, el) = select.select([], [outfd], [outfd])
        if outfd in wl:
            length = posix.write(outfd, self.out_buf[outfd])
            self.out_buf[outfd] = self.out_buf[outfd][length:]
            if not self.out_buf[outfd]:
                self.select_for_read(outfd)
                del self.out_buf[outfd]
        elif outfd in el:
            raise Exception('could not flush fd')
Esempio n. 28
0
 async def _write(self):
     while True:
         await asyncio.sleep(1 / 1000)
         if self.fd != -1:
             byte = await self._tx.get()
             try:
                 res = posix.write(
                     self.fd, bytearray([byte] + [0 for _ in range(63)]))
             except OSError:
                 print(sys.exc_info())
             else:
                 self._timer = self.timeout_ms
                 print(res)
             self._tx.task_done()
Esempio n. 29
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 */
        posix.write(fd, b'\x03\x00\x04')
        time.sleep(0.0016)  #Wait at least 1.5ms for result

        data = bytearray(posix.read(fd, 8))

        # Check data[0] and data[1]
        if data[0] != 0x03 or data[1] != 0x04:
            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]):
            raise Exception("CRC failed")

        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)
Esempio n. 30
0
    def write(self, addr, value):
        if isinstance(addr, EnumMeta) and hasattr(addr, "ADDR"):
            addr = addr.ADDR.value
        if isinstance(value, Enum):
            value = value.value

        msg = struct.pack('B', addr)

        if isinstance(value, bytes):
            msg += value
        else:
            msg += struct.pack("B" * len(value), *value)

        if posix.write(self.fd, msg) != len(msg):
            raise Exception()
Esempio n. 31
0
    def _ApplyRedirect(self, r, waiter):
        ok = True

        if r.tag == redirect_e.PathRedirect:
            if r.op_id in (Id.Redir_Great, Id.Redir_AndGreat):  # >   &>
                # NOTE: This is different than >| because it respects noclobber, but
                # that option is almost never used.  See test/wild.sh.
                mode = posix.O_CREAT | posix.O_WRONLY | posix.O_TRUNC
            elif r.op_id == Id.Redir_Clobber:  # >|
                mode = posix.O_CREAT | posix.O_WRONLY | posix.O_TRUNC
            elif r.op_id in (Id.Redir_DGreat, Id.Redir_AndDGreat):  # >>   &>>
                mode = posix.O_CREAT | posix.O_WRONLY | posix.O_APPEND
            elif r.op_id == Id.Redir_Less:  # <
                mode = posix.O_RDONLY
            else:
                raise NotImplementedError(r.op_id)

            # NOTE: 0666 is affected by umask, all shells use it.
            try:
                target_fd = posix.open(r.filename, mode, 0666)
            except OSError as e:
                util.error("Can't open %r: %s", r.filename,
                           posix.strerror(e.errno))
                return False

            # Apply redirect
            if not self._PushDup(target_fd, r.fd):
                ok = False

            # Now handle the extra redirects for aliases &> and &>>.
            #
            # We can rewrite
            #   stdout_stderr.py &> out-err.txt
            # as
            #   stdout_stderr.py > out-err.txt 2>&1
            #
            # And rewrite
            #   stdout_stderr.py 3&> out-err.txt
            # as
            #   stdout_stderr.py 3> out-err.txt 2>&3
            if ok:
                if r.op_id == Id.Redir_AndGreat:
                    if not self._PushDup(r.fd, 2):
                        ok = False
                elif r.op_id == Id.Redir_AndDGreat:
                    if not self._PushDup(r.fd, 2):
                        ok = False

            posix.close(target_fd)  # We already made a copy of it.
            # I don't think we need to close(0) because it will be restored from its
            # saved position (10), which closes it.
            #self._PushClose(r.fd)

        elif r.tag == redirect_e.DescRedirect:  # e.g. echo hi 1>&2

            if r.op_id == Id.Redir_GreatAnd:  # 1>&2
                if not self._PushDup(r.target_fd, r.fd):
                    ok = False
            elif r.op_id == Id.Redir_LessAnd:  # 0<&5
                # The only difference between >& and <& is the default file
                # descriptor argument.
                if not self._PushDup(r.target_fd, r.fd):
                    ok = False
            else:
                raise NotImplementedError

        elif r.tag == redirect_e.HereRedirect:
            # NOTE: Do these descriptors have to be moved out of the range 0-9?
            read_fd, write_fd = posix.pipe()

            if not self._PushDup(read_fd, r.fd):  # stdin is now the pipe
                ok = False

            # We can't close like we do in the filename case above?  The writer can
            # get a "broken pipe".
            self._PushClose(read_fd)

            thunk = _HereDocWriterThunk(write_fd, r.body)

            # TODO: Use PIPE_SIZE to save a process in the case of small here docs,
            # which are the common case.  (dash does this.)
            start_process = True
            #start_process = False

            if start_process:
                here_proc = Process(thunk)

                # NOTE: we could close the read pipe here, but it doesn't really
                # matter because we control the code.
                # here_proc.StateChange()
                pid = here_proc.Start()
                # no-op callback
                waiter.Register(pid, here_proc.WhenDone)
                #log('Started %s as %d', here_proc, pid)
                self._PushWait(here_proc, waiter)

                # Now that we've started the child, close it in the parent.
                posix.close(write_fd)

            else:
                posix.write(write_fd, r.body)
                posix.close(write_fd)

        return ok
Esempio n. 32
0
    def __setitem__(self, key, value):
        msg = struct.pack('BB', key, value)

        if posix.write(self.fd, msg) != 2:
            raise Exception()
Esempio n. 33
0
 def send(self, sMessage):
     if (self.wHandle != None):
         posix.write(self.wHandle.fileno(), sMessage)
         self.wHandle.flush()
Esempio n. 34
0
import __nemesys__
import posix

posix.write(1, __nemesys__.module_source(__name__))
Esempio n. 35
0
 def ReceiveEtherPacketOn(self, netid, packet):
     posix.write(self.tuns[netid].fileno(), str(packet))
 def ReceiveEtherPacketOn(self, netid, packet):
   posix.write(self.tuns[netid].fileno(), str(packet))
 def SendPacket(self, packet):
   packet = scapy.Ether(src=self._routermac, dst=self._mymac) / packet
   try:
     posix.write(self._tun.fileno(), str(packet))
   except ValueError:
     pass
Esempio n. 38
0
 def _write_command(self, cmd: int) -> None:
     ret = posix.write(self._fd, struct.pack(">H", cmd))
     if ret != 2:
         raise CommunicationError("Failed to write two-byte I2C command, "
                                  "write returned {}".format(ret))
Esempio n. 39
0
	def writeSomeData(self, data):
		try:
			setBlocking(False,1)
			return write(1,data)
		finally:
			setBlocking(True,1)
Esempio n. 40
0
import fcntl
 def SendPacket(self, packet):
   packet = scapy.Ether(src=self._routermac, dst=self._mymac) / packet
   try:
     posix.write(self._tun.fileno(), str(packet))
   except ValueError:
     pass
Esempio n. 42
0
 def write(self, data):
     dummy = posix.write(self.fd, data)
Esempio n. 43
0
	def write(self, data):
		dummy = posix.write(self.fd, data)