def spawn(self): # modified environment for instrumented child process environ = os.environ.copy() # set up random number generator environ['SAMPLER_SPARSITY'] = str(self.__sparsity) # set up reporting self.__pipe = os.pipe() environ['SAMPLER_FILE'] = '/dev/fd/%d' % self.__pipe[1] environ['SAMPLER_REPORT_FD'] = '%d' % self.__pipe[1] environ['GNOME_DISABLE_CRASH_DIALOG'] = '1' environ['SAMPLER_REAL_EXECUTABLE'] = self.app.executable # away we go! self.spawnEnv(environ) # tidy up pipe ends os.close(self.__pipe[1]) flags = fcntl(self.__pipe[0], F_GETFD) if flags >= 0: flags |= FD_CLOEXEC fcntl(self.__pipe[0], F_SETFD, flags) return
def m(): ot,nt=tcgetattr(stdin.fileno()),tcgetattr(stdin.fileno());nt[3]=nt[3] & ~ICANON & ~ECHO;tcsetattr(stdin.fileno(),TCSANOW,nt);of=fcntl(stdin.fileno(),F_GETFL);fcntl(stdin.fileno(),F_SETFL,of|os.O_NONBLOCK) try: while 1: try:c=stdin.read(1);break except IOError:pass finally:tcsetattr(stdin.fileno(),TCSAFLUSH,ot);fcntl(stdin.fileno(),F_SETFL,of);return c
def start(self): fcntl(self.conn.sock.fileno(),F_SETOWN,getpid()) flgs = fcntl(self.conn.sock.fileno(),F_GETFL,0) fcntl(self.conn.sock.fileno(),F_SETFL,flgs | 0x0040 | 0x0004) # O_ASYNC | O_NONBLOCK signal(SIGALRM,handler) signal(SIGIO,iohandler) alarm(Bot.delay) self.listen()
def _mmcallback(self, read, fcntl, FCNTL): # set in non-blocking mode dummy = fcntl(self._mmfd, FCNTL.F_SETFL, FCNTL.O_NDELAY) # read a byte devval = read(self._mmfd, 1) # set in blocking mode dummy = fcntl(self._mmfd, FCNTL.F_SETFL, 0) # return if nothing read if not devval: return devval = ord(devval) dev, val = devval >> 2, devval & 3 if self._mm_callbacks.has_key(dev): func = self._mm_callbacks[dev] func(val) else: print 'Warning: unknown device in mmcallback'
def m(): ot, nt = tcgetattr(stdin.fileno()), tcgetattr(stdin.fileno()) nt[3] = nt[3] & ~ICANON & ~ECHO tcsetattr(stdin.fileno(), TCSANOW, nt) of = fcntl(stdin.fileno(), F_GETFL) fcntl(stdin.fileno(), F_SETFL, of | os.O_NONBLOCK) try: while 1: try: c = stdin.read(1) break except IOError: pass finally: tcsetattr(stdin.fileno(), TCSAFLUSH, ot) fcntl(stdin.fileno(), F_SETFL, of) return c
def recv(self): fcntl(self.fd, F_SETFL, O_NONBLOCK) while 1: # find 0x7e 0x00 while 1: # find 0x7e, exit if no chars addr1 = self.readone() if addr1 == None: return if addr1 == '\x7e': break # wait for 0x00 addr2 = self.readone_delay() if addr2 == None: return if addr2 == '\0': break # We have a header, try and get the whole message msg = addr1 + addr2 for i in range(0, Message.MSG_SIZE - len(msg)): char = self.readone_delay() if char == None: return msg = msg + char return Message(msg)
# THIS SOFTWARE IS PROVIDED BY MATT CHAPUT ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO # EVENT SHALL MATT CHAPUT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # The views and conclusions contained in the software and documentation are # those of the authors and should not be interpreted as representing official # policies, either expressed or implied, of Matt Chaput. """ This module contains classes implementing exclusive locks for platforms with fcntl (UNIX and Mac OS X) and Windows. Whoosh originally used directory creation as a locking method, but it had the problem that if the program crashed the lock directory was left behind and would keep the index locked until it was cleaned up. Using OS-level file locks fixes this. """ import errno import os import sys import time def try_for(fn, timeout=5.0, delay=0.1): """Calls ``fn`` every ``delay`` seconds until it returns True or
args[i] = '"{}"'.format(arg) res = spawnv(P_WAIT, filename, args) _exit_code[0] = res raise SystemExit(res) # A fake fcntl module which is false, but can fake out RPython class fcntl: LOCK_SH = 0 def flock(self, fd, mode): pass def __nonzero__(self): return False fcntl = fcntl() else: raise RuntimeError("unsupported platform: " + sys.platform) if __rpython__: # RPython provides ll hooks for the actual os.environ object, not the # one we pulled out of "nt" or "posix". from os import environ # RPython doesn't have access to the "sys" module, so we fake it out. # The entry_point function will set these value appropriately. _sys = sys class sys: platform = _sys.platform
pass # Ensure all arguments are quoted (to allow spaces in paths) for i, arg in enumerate(args): if arg[0] != "\"" and args[-1] != "\"": args[i] = "\"{}\"".format(arg) res = spawnv(P_WAIT,filename, args) _exit_code[0] = res raise SystemExit(res) # A fake fcntl module which is false, but can fake out RPython class fcntl: LOCK_SH = 0 def flock(self,fd,mode): pass def __nonzero__(self): return False fcntl = fcntl() else: raise RuntimeError("unsupported platform: " + sys.platform) if __rpython__: # RPython provides ll hooks for the actual os.environ object, not the # one we pulled out of "nt" or "posix". from os import environ # RPython doesn't have access to the "sys" module, so we fake it out. # The entry_point function will set these value appropriately. _sys = sys class sys: platform = _sys.platform executable = _sys.executable
# THIS SOFTWARE IS PROVIDED BY MATT CHAPUT ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO # EVENT SHALL MATT CHAPUT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # The views and conclusions contained in the software and documentation are # those of the authors and should not be interpreted as representing official # policies, either expressed or implied, of Matt Chaput. """ This module contains classes implementing exclusive locks for platforms with fcntl (UNIX and Mac OS X) and Windows. Whoosh originally used directory creation as a locking method, but it had the problem that if the program crashed the lock directory was left behind and would keep the index locked until it was cleaned up. Using OS-level file locks fixes this. """ import errno import os import time def try_for(fn, timeout=5.0, delay=0.1): """Calls ``fn`` every ``delay`` seconds until it returns True or ``timeout`` seconds elapse. Returns True if the lock was acquired, or False if the
# Open TUN device file, create tap0 # # To open a new transient device, put "tap%d" into ioctl() below. # To open a persistent device, use "tap0" or the actual full name. # # You can create a persistent device with "openvpn --mktun --dev tap0". # This device will show up on ifconfig, but will have "no link" unless # it is opened by this or similar script even if you bring it up with # "ifconfig tap0 up". This can be confusing. # # Copied from https://gist.github.com/glacjay/585369 # IFF_NO_PI is important! Otherwise, tap will add 4 extra bytes per packet, # and this will confuse Scapy parsing. tun = os.open("/dev/net/tun", os.O_RDWR) print "struct pack!: ", fcntl(tun, TUNSETIFF, struct.pack("16sH", "tap0", TUNMODE | IFF_NO_PI)) ifs = ioctl(tun, TUNSETIFF, struct.pack("16sH", "tap0", TUNMODE | IFF_NO_PI)) ifname = ifs[:16].strip("\x00") # will be tap0 # Optionally, we want tap0 be accessed by the normal user. fcntl.ioctl(tun, TUNSETOWNER, 1000) print "Allocated interface %s. Configuring it." % ifname subprocess.check_call("ifconfig %s down" % ifname, shell=True) subprocess.check_call("ifconfig %s hw ether 12:67:7e:b7:6d:c8" % ifname, shell=True) subprocess.check_call( "ifconfig %s 10.5.0.1 netmask 255.255.255.0 broadcast 10.5.0.255 up" %
import os import sys import select import time from fcntl import * from game_memo import * rpipe, wpipe = os.pipe() wpipe = os.fdopen(wpipe, "w") rpipe = os.fdopen(rpipe, "r") flags = fcntl(rpipe, F_GETFL) fcntl(rpipe, F_SETFL, flags | os.O_NONBLOCK) pid = os.fork() if pid == 0: rpipe.close() wpipe.write("hello") wpipe.flush() root = Tk() root.title("Hanabi Memo") app = GUIDemo(master=root, pipe=wpipe, player_num=4, ID=0) app.mainloop() print("Child finish") else: print("parent")
def sJudge(hanabi_addr, rID, jport): #TODO maybe should have some arguments...? print ('[judge ' + str(rID) + '] inside judge XD') print ('Now connect to ' + str(hanabi_addr) + ':' + str(jport) + '...') jsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) jsock.connect((str(hanabi_addr), jport)) gameID = -1 game_player_num = -1 while (True): # game init print ('[judge ' + str(rID) + '] waiting for judge command...') (inputready, outputready, exceptrdy) = select.select([0, ssock, jsock], [], [], 1) ok = False for i in inputready: if i == 0: data = input() print ('[judge ' + str(rID) + '] what you type is \'' + data + '\'') #TODO... elif i == ssock: data = ssock.recv(4096) # take those msg, it must be 'startgame portID' print ('[judge ' + str(rID) + '] recv from ssock \'' + data.decode('UTF-8') + '\'') time.sleep(2) tmp = 'startgame ACK' ssock.send(tmp.encode('UTF-8')) elif i == jsock: data = jsock.recv(4096) print ('[judge ' + str(rID) + '] recv from jsock \'' + data.decode('UTF-8') + '\'') time.sleep(2) buff = data.decode('UTF-8') game_init = buff buf = buff.split(" ") if (buf[0] == 'startgame'): # stargame and serve result ok = True gameID = int(buf[1]) game_player_num = int(buf[2]) # handle serve result ''' for i in range(game_player_num): print("player" + str(i) + ": ") for j in range(4): print(" (" + str(buf[2+8*i+2*j+1]) + ", " + str(buf[2+8*i+2*j+2]) + ")") ''' break if (ok == True): break print ('Now initial Game class...') G = game.Game(player_num=game_player_num, buf=buff, playerID=gameID) G.show_status() # tkinter if os.environ.get('DISPLAY') != None: tkflag = 1 else: tkflag = 0 if tkflag == 1: rpipe, wpipe = os.pipe() wpipe = os.fdopen(wpipe, "w") rpipe = os.fdopen(rpipe, "r") flags = fcntl(rpipe, F_GETFL) fcntl(rpipe, F_SETFL, flags | os.O_NONBLOCK) pid = os.fork() if pid == 0: rpipe.close() if os.environ.get('DISPLAY') != None: root = Tk() root.title("Hanabi Memo") app = GUIDemo(master=root, pipe=wpipe, player_num=game_player_num, ID=gameID) app.mainloop() exit() wpipe.close() # select read rqueue = [0, jsock] if tkflag == 1: rqueue.append(rpipe) while (True): # game loop print ('[judge ' + str(rID) + '] inside game loop XD') (inputready, outputready, exceptrdy) = select.select(rqueue, [], []) EndGame = False for i in inputready: if i == 0: print ('TODO...') elif i == jsock: data = jsock.recv(4096) msg = data.decode('UTF-8') msg_list = msg.split(' ') if msg_list[0] == "yourturn": while (True): # select stdin or pipe if tkflag == 1: while 1: rlist, wlist, elist = select.select([0,rpipe], [], []) if rlist[0] == rpipe: # pipe from tkinter msg = rpipe.read(4096) if len(msg) != 0: data = msg break else: data = input("Your turn: ") break else: data = input("Your turn: ") cmd_list = data.split(' ') if cmd_list[0] == "hit" and len(cmd_list) == 2: cardidx = int(cmd_list[1]) info = "hit " + str(cardidx) print(" Send:" + info) jsock.send(info.encode('UTF-8')) break elif cmd_list[0] == "hint" and len(cmd_list) == 4: hplayer = int(cmd_list[1]) htype = int(cmd_list[2]) hnumber = int(cmd_list[3]) info = "hint " + str(hplayer) + " " + str(htype) + " " + str(hnumber) print(" Send: " + info) jsock.send(info.encode('UTF-8')) break elif cmd_list[0] == "throw" and len(cmd_list) == 2: cardidx = int(cmd_list[1]) info = "throw " + str(cardidx) print(" Send: " + info) jsock.send(info.encode('UTF-8')) break else: print("Wrong input format: [hit, hint, throw]") elif msg_list[0] == "hit": print ('hit TODO...') print ('recv from server ' + msg) G.hit(player=int(msg_list[1]), cardidx=int(msg_list[2]), \ card_old=(int(msg_list[3]), int(msg_list[4])), card_new=(int(msg_list[5]), int(msg_list[6]))) elif msg_list[0] == "hint": print ('hint TODO...') print ('recv from server ' + msg) res = [] for i in range(int(msg_list[5])): res.append(int(msg_list[6 + i])) G.hint(sender=int(msg_list[1]), recver=int(msg_list[2]), \ hinttype=int(msg_list[3]), number=int(msg_list[4]), card_idx=res) elif msg_list[0] == "throw": print ('throw TODO...') print ('recv from server ' + msg) G.throw(player=int(msg_list[1]), cardidx=int(msg_list[2]), card_old=(int(msg_list[3]), int(msg_list[4])), card_new=(int(msg_list[5]), int(msg_list[6]))) elif msg_list[0] == "endgame": print ('endgame TODO...') #ttt = 'endgame ACK' #jsock.send(ttt.encode('UTF-8')) #time.sleep(0.5) EndGame = True break else: print ('recv nani?') if (msg_list[0] == "hit" or msg_list[0] == "hint" or msg_list[0] == "throw"): ttt = 'action ACK' jsock.send(ttt.encode('UTF-8')) print ('>>>>>>>>>>>>>>> DEBUG >>>>>>>>>>>>>>>') G.show_status() print ('>>>>>>>>>>>>>>> DEBUG >>>>>>>>>>>>>>>') if (EndGame == True): break jsock.close()
def send(self, msg): #msg.prt() msg = msg.tostring() assert len(msg) == Message.MSG_SIZE fcntl(self.fd, F_SETFL, 0) write(self.fd, msg)
# 'shell=True' is needed to see when the child segfaults. p = Popen([exe], stdin=PIPE, stdout=PIPE, shell=True) p.stdin.write(bf_commands(libc_hash)) base = get_base(libc_hash, p.stdout) p.stdin.write(bf_input_addr(libc_hash, base)) p.stdin.write(bf_input_rop(libc_hash, base)) # Capture the exit code. # sys.stdout.write("exit: " + p.stdout.read()) # Interact with stdin. # http://eyalarubas.com/python-subproc-nonblock.html s = p.stdout flags = fcntl(s.fileno(), F_GETFL) res = fcntl(s, F_SETFL, flags | O_NONBLOCK) # while True: # res = "" # try: # cmd = sys.stdin.readline() # p.stdin.write(cmd) # sleep(0.1) # XXX: race condition # while True: # c = p.stdout.read(1) # res += c # except (IOError, OSError) as e: # no more data # sys.stdout.write(res)
#!/bin/python import os import signal from fcntl import * FNAME = "." def handler(signum, frame): print "File %s modified" % (FNAME,), print signum, frame signal.signal(signal.SIGIO, handler) fd = os.open(FNAME, os.O_RDONLY) fcntl(fd, F_SETSIG, 0) fcntl(fd, F_NOTIFY, DN_MODIFY | DN_CREATE | DN_MULTISHOT) while True: pass