def run(self): mqverifT = [] mqcards = sysv_ipc.MessageQueue(100) mqhandsize = sysv_ipc.MessageQueue(300) mqaffichage = sysv_ipc.MessageQueue(400) mains = [] players = [] keys = [] for i in range(self.nbjoueurs): mains.append([]) keys.append(i + 1) mqverif = sysv_ipc.MessageQueue(keys[i]) mqverifT.append(mqverif) for j in range(1, 6): mains[i].append(self.deck.get()) mains[i][j - 1].numerojoueur = i + 1 players.append(Players(i + 1, self.deck, mains[i], self.printlock)) for x in players: x.start() with self.printlock: threadaffichage = threading.Thread(target=self.affichageforce, args=(mqaffichage, mqverifT)) threadaffichage.start() while True: mqaffichage.send(str(1).encode(), type=4) carterecue, t = mqcards.receive() self.verification(loads(carterecue), mqverifT, mqhandsize, mqaffichage)
def __init__(self, key_in=124, key_out=123): threading.Thread.__init__(self) self.running = 0 self.key_in = key_in self.q_in = ipc.MessageQueue(self.key_in, ipc.IPC_CREAT) self.key_out = key_out self.q_out = ipc.MessageQueue(self.key_out, ipc.IPC_CREAT)
def run(self): mqcards = sysv_ipc.MessageQueue(100) mqverif = sysv_ipc.MessageQueue(self.numero) # Message queue key numero joueur, sert à recevoir TRUE ou FALSE mqtouchejouee = sysv_ipc.MessageQueue(200 + self.numero) mqhandsize = sysv_ipc.MessageQueue(300) mqaffichage = sysv_ipc.MessageQueue(400) threadaffichage = threading.Thread(target=self.affichageforce, args=(mqaffichage, )) threadaffichage.start() while len(self.cartesmain) != 0 and not self.deck.empty(): timer = multitimer.MultiTimer(interval=10, function=self.pioche, kwargs={"mqaffichage": mqaffichage}, runonstart=False) timer.start() erreur = True numcarte = 0 while erreur: try: bnumcarte, t = mqtouchejouee.receive() numcarte = int(bnumcarte.decode()) mqcards.send(dumps(self.cartesmain[numcarte - 1])) erreur = False except IndexError: print("Joueur : " + str(self.numero) + " | Veuillez entrer une touche valide") timer.stop() blebool, t = mqverif.receive() lebool = blebool.decode() == 'True' if lebool: self.removecard(self.cartesmain[numcarte - 1]) mqhandsize.send((str(len(self.cartesmain))).encode()) else: self.pioche(mqaffichage) threadaffichage.join()
def run_tests(): print("running home tests") homes_queue = sysv_ipc.MessageQueue(key=None, flags=sysv_ipc.IPC_CREX) market_queue = sysv_ipc.MessageQueue(key=None, flags=sysv_ipc.IPC_CREX) print(f"MARKET_KEY = {market_queue.key}\nHOME_KEY = {homes_queue.key}") home_count = 2 # homes = [Home((i, home_count), 100, 1000, policies[0]) for i in range(0, home_count)] homes = [ Home(id_count_tuple=(0, 3), interval=5, slot_timeout=10, policy=new_policy(behaviour=Behaviours.ALWAYS_GIVE, initial_cons=50, initial_prod=150)), ] deployer = HomeDeployer(100, homes_queue_key=homes_queue.key, market_queue_key=market_queue.key, homes=homes) deployer.deploy().start() deployer.process.join()
def test_remove_message_queue(self): """Exercise remove_message_queue()""" mq = sysv_ipc.MessageQueue(None, sysv_ipc.IPC_CREX) sysv_ipc.remove_message_queue(mq.id) with self.assertRaises(sysv_ipc.ExistentialError): sysv_ipc.MessageQueue(mq.key)
def createMQ(key): try: mq = sysv_ipc.MessageQueue(key, sysv_ipc.IPC_CREX) except sysv_ipc.ExistentialError: mq = sysv_ipc.MessageQueue(key, sysv_ipc.IPC_CREAT) mq.remove() mq = sysv_ipc.MessageQueue(key, sysv_ipc.IPC_CREAT) return mq
def __init__(self, queue_id): "queue_id: the integer id of the queue to be used" self.queue_id = queue_id pc = ravel.profiling.PerfCounter("mq_connect") pc.start() try: self.mq = sysv_ipc.MessageQueue(self.queue_id, mode=0777) except sysv_ipc.ExistentialError, e: logger.warning("queue {0} does not exist: {1}".format( self.queue_id, e)) self.mq = sysv_ipc.MessageQueue(self.queue_id, sysv_ipc.IPC_CREAT, mode=0777)
def clear_queue(queue_id): try: mq = sysv_ipc.MessageQueue(queue_id, sysv_ipc.IPC_CREAT, mode=0777) mq.remove() except sysv_ipc.PermissionsError: logger.warning( "could not clear clear message queue {0}".format(queue_id))
def __init__(self): # create queue, and fail if it does not already exist no = int(open(QUEUE_FILE).read()) self._mqueue = sysv_ipc.MessageQueue(no) # internal queue for holding messages which can't be sent because # the message queue was full self._internal_queue = []
class GraficadorTest: READ = 4 DATOS_GRAFICADOR = 5 PIPE_MAX_SIZE = 4096 try: mq = sysv_ipc.MessageQueue(key=3333, flags=0, mode=int("0600", 8), max_message_size=2048) except sysv_ipc.ExistentialError: print("La Interfaz no ha sido inicializada!") exit(0) @classmethod def start(cls): try: while (True): id_grupo = bytes([int(input("Inserte ID grupo: "))]) id_sensor = bytes([int(input("Inserte ID sensor: "))]) cls.mq.send(pack('ssss', id_grupo, b'\x00', b'\x00', id_sensor), type=cls.READ) #cls.mq.send(pack('ssss', b'\x01', b'\x00', b'\x00',b'\x01'), type = cls.READ) msg, tipo = cls.mq.receive(block=True, type=cls.DATOS_GRAFICADOR) with open("datos_graficador.bin", "rb") as f: sensor_data = f.read() print(sensor_data) except KeyboardInterrupt: print("\nGraficador Finalizado...")
def upload(): upload = request.files['file'] if upload: filename = upload.filename upload.save(os.path.join('downloads', filename)) app.logger.debug('File is saved as %s', filename) try: q = ipc.MessageQueue(19640419001, ipc.IPC_CREAT | ipc.IPC_EXCL) except: q = ipc.MessageQueue(19640419001) q.send('/home/shenwei/nebula/python-proc/downloads/%s' % filename, block=False) return "Done" return "Error"
def __init__(self): Receiver.__init__(self) ResReceiver.logger.info("ResReceiver Init") try: myQueId = 0 if ResReceiver.myQueue is None: #IPC_CREAT : create or return key if it is allocated. #IPC_CREX : IPC_CREAT | IPC_EXCL #IPC_EXCL : return -1 if there is already allocated. myQueId = int(ConfManager.getInstance().getConfigData( ConfManager.MSGQUEUE_INFO, "RESTIF_S")) maxQSize = ConfManager.getInstance().getConfigData( ConfManager.MSGQUEUE_INFO, "MAX_QUEUE_SIZE") #ResReceiver.myQueue = sysv_ipc.MessageQueue(myQueId, sysv_ipc.IPC_CREAT, mode=0777, max_message_size = int(maxQSize) ) ResReceiver.myQueue = sysv_ipc.MessageQueue( myQueId, sysv_ipc.IPC_CREAT) self.resReceiver = self self.resReceiver.start() except Exception as e: ResReceiver.logger.error( "msgQueue Connection Failed.. RESTIF_S QUEUE_ID[%d] SIZE[%s] %s" % (myQueId, maxQSize, e)) return None
def __init__(self, key): self.queue = sysv_ipc.MessageQueue( key=key, flags=sysv_ipc.IPC_CREAT, mode=0600, max_message_size=MAXIMUM_EVENT_SIZE, )
def mq_push(mq_key, mq_type, dataid): import struct import sysv_ipc print 'sending dataid %s to MQ:' % (dataid, ) mq = sysv_ipc.MessageQueue(mq_key, flags=sysv_ipc.IPC_CREAT, mode=0666) mq.send(struct.pack('<i', dataid), block=True, type=mq_type)
def get_queue(qid=None): r"""Create or return a sysv_ipc.MessageQueue and register it. Args: qid (int, optional): If provided, ID for existing queue that should be returned. Defaults to None and a new queue is returned. Returns: :class:`sysv_ipc.MessageQueue`: Message queue. """ if _ipc_installed: kwargs = dict(max_message_size=tools.get_YGG_MSG_MAX()) if qid is None: kwargs['flags'] = sysv_ipc.IPC_CREX try: mq = sysv_ipc.MessageQueue(qid, **kwargs) except sysv_ipc.ExistentialError as e: # pragma: debug raise sysv_ipc.ExistentialError("%s: %s" % (e, qid)) key = str(mq.key) IPCComm.register_comm(key, mq) return mq else: # pragma: windows logger.warning("IPC not installed. Queue cannot be returned.") return None
def test_remove(self): """tests that mq.remove() works""" self.mq.remove() with self.assertRaises(sysv_ipc.ExistentialError): sysv_ipc.MessageQueue(self.mq.key) # Wipe this out so that self.tearDown() doesn't crash. self.mq = None
def run(self): global my_mq my_mq = sysv_ipc.MessageQueue(100 + self.id) # Thread gérant les actions du joueur play_t = Thread(target=self.next_move) play_t.start() # Thread gérant l'envoi de la première notification (initialisation de la partie) notify_t = Thread(target=self.notify, args=()) notify_t.start() while True: # print("Waiting - board from board") message, t = my_mq.receive() data = message.decode() if data == "draw": # print("Warning - Board didn't accept last move.") self.draw_card() notify_t = Thread(target=self.notify, args=()) notify_t.start() else: new_board = string_to_card(data) if new_board != self.board: self.board = new_board if self.board in self.hand: self.hand.remove(self.board) if len(self.hand) == 0: self.winner.value = self.id notify_t = Thread(target=self.notify, args=()) notify_t.start()
def test_randomly_generated_key(self): """tests that the randomly-generated key works""" # This is tested implicitly elsewhere but I want to test it explicitly mq = sysv_ipc.MessageQueue(None, sysv_ipc.IPC_CREX) self.assertIsNotNone(mq.key) self.assertGreaterEqual(mq.key, sysv_ipc.KEY_MIN) self.assertLessEqual(mq.key, sysv_ipc.KEY_MAX) mq.remove()
def report(self): "Report the performance counter by adding it to the message queue" try: if is_profiled(): mq = sysv_ipc.MessageQueue(ProfileQueueId, mode=0777) mq.send(pickle.dumps(self)) except Exception, e: print e
def test_kwargs(self): """ensure init accepts keyword args as advertised""" # mode 0x180 = 0600. Octal is difficult to express in Python 2/3 compatible code. mq = sysv_ipc.MessageQueue(None, flags=sysv_ipc.IPC_CREX, mode=0x180, max_message_size=256) mq.remove()
def get_ipc_queue(ipc_key: int) -> sysv_ipc.MessageQueue: """ Create an IPC message queue given an ID. If it already exists, remove it using the os primitive and create if again :param ipc_key: the IPC Message Queue key id :return: the MessageQueue Object """ try: message_queue = sysv_ipc.MessageQueue(ipc_key, sysv_ipc.IPC_CREX) except sysv_ipc.ExistentialError: print( f"{Fore.BLUE}Message queue {ipc_key} already exists, recreating it.{Style.RESET_ALL}" ) sysv_ipc.MessageQueue(ipc_key).remove() message_queue = sysv_ipc.MessageQueue(ipc_key, sysv_ipc.IPC_CREX) return message_queue
def __init__( self, ip_adress, port_number): #Podria recibir el path del archivo de donde lee self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.server_address = (ip_adress, port_number) self.frecuencia = 1 self.mq = sysv_ipc.MessageQueue(2525, sysv_ipc.IPC_CREAT, int("0600", 8), 2048)
def main(): KEY = 81 print("KEY:", KEY) mq = sysv_ipc.MessageQueue(KEY) print("id:", mq.id) print("ready to receive messages.") while True: mtext, mtype = mq.receive(type=1) print(mtext.decode("utf-8"))
def __init__(self, master): self.config = master.config try: self.configConfig = master.config["config"] except KeyError: self.configConfig = {} self.debugLevel = self.configConfig.get("debugLevel", 0) self.master = master try: self.configIPC = master.config["control"]["IPC"] except KeyError: self.configIPC = {} self.status = self.configIPC.get("enabled", False) # Unload if this module is disabled or misconfigured if not self.status: self.master.releaseModule("lib.TWCManager.Control", "WebIPCControl") return None # Create an IPC (Interprocess Communication) message queue that we can # periodically check to respond to queries from the TWCManager web interface. # # These messages will contain commands like "start charging at 10A" or may ask # for information like "how many amps is the solar array putting out". # # The message queue is identified by a numeric key. This script and the web # interface must both use the same key. The "ftok" function facilitates creating # such a key based on a shared piece of information that is not likely to # conflict with keys chosen by any other process in the system. # # ftok reads the inode number of the file or directory pointed to by its first # parameter. This file or dir must already exist and the permissions on it don't # seem to matter. The inode of a particular file or dir is fairly unique but # doesn't change often so it makes a decent choice for a key. We use the parent # directory of the TWCManager script. # # The second parameter to ftok is a single byte that adds some additional # uniqueness and lets you create multiple queues linked to the file or dir in # the first param. We use 'T' for Tesla. # # If you can't get this to work, you can also set key = <some arbitrary number> # and in the web interface, use the same arbitrary number. While that could # conflict with another process, it's very unlikely to. self.webIPCkey = sysv_ipc.ftok(self.config["config"]["settingsPath"], ord("T"), True) # Use the key to create a message queue with read/write access for all users. self.webIPCqueue = sysv_ipc.MessageQueue(self.webIPCkey, sysv_ipc.IPC_CREAT, 0o666) if self.webIPCqueue == None: self.master.debugLog( 1, "WebIPCCtrl", "ERROR: Can't create Interprocess Communication message queue to communicate with web interface.", )
def to_c(self): try: message_queue = sysv_ipc.MessageQueue(-1) send_message(message_queue, self.html_content) receive_messages(message_queue) except sysv_ipc.ExistentialError: print( "Message queue not initialized. Please run the C programfirst") print("To C Clicked()")
def clearSysVIPC(self): msgque = sysv_ipc.MessageQueue(STRANDMGR_MSGQUE_KEY, sysv_ipc.IPC_CREAT) msgque.remove() # create a bunch of semaphores and destroy them to ensure semaphores named by # keys used by the manager don't exist. for i in range(20): semaphore = sysv_ipc.Semaphore(STRANDMGR_SEM_KEY_BASE + i, sysv_ipc.IPC_CREAT) semaphore.remove()
def __init__(self, key: int): try: self.message_queue = sysv_ipc.MessageQueue(key) except sysv_ipc.ExistentialError: print(f"Cannot connect to message queue {key}, terminating.") sys.exit(1) print( 'Connection established. Enter "report" to see the current state of the simulation,' 'or "end" to end the simulation')
def test_max_message_size_respected(self): '''ensure the max_message_size param is respected''' mq = sysv_ipc.MessageQueue(None, sysv_ipc.IPC_CREX, max_message_size=10) with self.assertRaises(ValueError): mq.send(b' ' * 11, block=False) mq.remove()
def send_to_C(self): # for conection with the C program sender = CDLL("./sender.so") receiver = CDLL("./receiver.so") sender.connect() receiver.connect() try: # file directory path dir_path = os.path.dirname(os.path.realpath(self.file_path)) file_name = os.path.relpath(self.file_path, dir_path) # initialize the queue print("before sender") sender.main() print("after sender") # put the key (integer) as parameter (in this case: -1) message_queue = sysv_ipc.MessageQueue(-1) # send the file name for output send_message(message_queue, str(file_name[:-4])) # we send chunks of 2000 bytes from the file no_of_full_chunks = int(len(self.html) / 2000) last_chunk = len(self.html) - no_of_full_chunks * 2000 chunks = [] # the list of chunks if no_of_full_chunks > 0: chunks = [ self.html[i:i + 2000] for i in range(0, no_of_full_chunks * 2000, 2000) ] chunks.append(self.html[-last_chunk:]) else: chunks.append(self.html) # we send the number of chunks and then the actual chunks send_message(message_queue, str(len(chunks))) for chunk in chunks: send_message(message_queue, chunk) print("before receiver") receiver.main() print("after receiver") except sysv_ipc.ExistentialError: print( "Message queue not initialized. Please run the C program first" )
def homes(weather, queue, running, amount=10, pol=GIVE): N = amount # NOMBRE DE MAISONS hom = list() for i in range(N): c = random.randrange(100, 520) p = random.randrange(50, 300) if pol == 4: pols = random.randrange(0,3,1) else: pols = pol hom.append(Process(target=home, args=( weather, queue, running, c, p, 2, pols))) for p in hom: p.start() print('Homes started') for p in hom: p.join() ptime.sleep(2) sysv_ipc.MessageQueue(2).remove() sysv_ipc.MessageQueue(3).remove() print('End of homes - See ya !')