def Setup(self): utils.say("Oooo 'ello, I'm Mrs. Premise!") self.Params = utils.read_params() try: self.Semaphore = sysv_ipc.Semaphore(self.Params["KEY"], sysv_ipc.IPC_CREX) except sysv_ipc.ExistentialError as err: self.Logger.debug(err) # One of my peers created the semaphore already self.Semaphore = sysv_ipc.Semaphore(self.Params["KEY"]) # Waiting for that peer to do the first acquire or release while not self.Semaphore.o_time: time.sleep(.1) else: # Initializing sem.o_time to nonzero value self.Semaphore.release() # Now the semaphore is safe to use. try: self.Memory = sysv_ipc.SharedMemory(self.Params["KEY"], sysv_ipc.IPC_CREX) except sysv_ipc.ExistentialError as err: self.Logger.debug(err) self.Memory = sysv_ipc.SharedMemory(self.Params["KEY"]) else: self.Memory.release() self.Logger.debug("Setup done") return True
def _run(self): # Obtain the keys for the shared memory and semaphores. keySharedMemory = sysv_ipc.ftok(self.name, 1, True) keySemMutex = sysv_ipc.ftok(self.name, 2, True) keySemCondition = sysv_ipc.ftok(self.name, 3, True) # Instantiate the SharedMemory and Semaphore objects. shm = sysv_ipc.SharedMemory(keySharedMemory) mutex = sysv_ipc.Semaphore(keySemCondition) cond = sysv_ipc.Semaphore(keySemCondition) while self.running: start = time.time() try: cond.Z(timeout=1) except: continue # with statement??? mutex.acquire() shm.attach() buf = shm.read() shm.detach() mutex.release() img = numpy.frombuffer(buf, numpy.uint8).reshape(480, 640, 4) self.on_data(img) elapsed_time = time.time() - start logger.info('%2.2f Hz', 1.0 / elapsed_time)
def test_remove_semaphore(self): """Exercise remove_semaphore()""" sem = sysv_ipc.Semaphore(None, sysv_ipc.IPC_CREX) sysv_ipc.remove_semaphore(sem.id) with self.assertRaises(sysv_ipc.ExistentialError): sysv_ipc.Semaphore(sem.key)
def remove_run(): mem = sysv_ipc.SharedMemory(1) mem.detach() mem.remove() server_semaphore = sysv_ipc.Semaphore(2) server_semaphore.remove() client_semaphore = sysv_ipc.Semaphore(3) client_semaphore.remove()
def get_semaphore(): try: semaphore = sysv_ipc.Semaphore(SEMAPHORE_KEY, sysv_ipc.IPC_CREX) except sysv_ipc.ExistentialError: semaphore = sysv_ipc.Semaphore(SEMAPHORE_KEY) while not semaphore.o_time: time.sleep(.1) else: semaphore.release() return semaphore
def initSemaphore(id): ''' initialization of semaphore that will lock the shared memory ''' global semaphore try: semaphore = ss.Semaphore( id, ss.IPC_CREAT) #this will look for already created semaphore except: semaphore = ss.Semaphore(id, ss.IPC_CREX) #this will create a new one return
def acquire(self, blocking=True, shared=False): if shared: raise tooz.NotImplemented if (blocking is not True and sysv_ipc.SEMAPHORE_TIMEOUT_SUPPORTED is False): raise tooz.NotImplemented("This system does not support" " semaphore timeouts") blocking, timeout = utils.convert_blocking(blocking) start_time = None if not blocking: timeout = 0 elif blocking and timeout is not None: start_time = time.time() while True: tmplock = None try: tmplock = sysv_ipc.Semaphore(self.key, flags=sysv_ipc.IPC_CREX, initial_value=1) tmplock.undo = True except sysv_ipc.ExistentialError: # We failed to create it because it already exists, then try to # grab the existing one. try: tmplock = sysv_ipc.Semaphore(self.key) tmplock.undo = True except sysv_ipc.ExistentialError: # Semaphore has been deleted in the mean time, retry from # the beginning! continue if start_time is not None: elapsed = max(0.0, time.time() - start_time) if elapsed >= timeout: # Ran out of time... return False adjusted_timeout = timeout - elapsed else: adjusted_timeout = timeout try: tmplock.acquire(timeout=adjusted_timeout) except sysv_ipc.BusyError: tmplock = None return False except sysv_ipc.ExistentialError: # Likely the lock has been deleted in the meantime, retry continue else: self._lock = tmplock return True
def client_run(): mem = sysv_ipc.SharedMemory(1) server_semaphore = sysv_ipc.Semaphore(2) client_semaphore = sysv_ipc.Semaphore(3) size = 1 << 20 duration = 10 end = time.time() + duration msgs = 0 while time.time() < end: server_semaphore.acquire() data = mem.read(size) client_semaphore.release() msgs += 1 mem.detach() print('Received {} messages in {} second(s).'.format(msgs, duration))
def stop(on_init: bool = False) -> None: am_i_root() config = Config() sem = None sem_id = get_sem_id() try: sem = sysv_ipc.Semaphore(sem_id) if not on_init: try: sem.acquire(60) except sysv_ipc.BusyError: warn( "Could not acquire semaphore, commencing stop action anyway..." ) systemd.daemon.notify("STOPPING=1") except sysv_ipc.ExistentialError: # Prevent systemd-swap from starting/stopping while cleaning up. sem = sysv_ipc.Semaphore(sem_id, flags=sysv_ipc.IPC_CREX) if not on_init: warn(f"{sys.argv[0]} might not be running") destroy_info = DestroyInfo.load() swap_units = find_swap_units() swap_unit_found = None for i in ["swapD", "swapFC", "Zram"]: for unit_path in filter(lambda u, ix=i: ix.lower() in read(u), swap_units): swapoff(unit_path, i) swap_unit_found = True if swap_unit_found: swap_units = find_swap_units() swap_unit_found = False if destroy_info: if os.path.isdir(f"{WORK_DIR}/zswap"): info("Zswap: restore configuration: start") for zswap_parameter, value in destroy_info.zswap_parameters.items( ): write(value, zswap_parameter) info("Zswap: restore configuration: complete") info("Removing working directory...") shutil.rmtree(WORK_DIR, ignore_errors=True) swapfc_path = config.get("swapfc_path") info(f"Removing files in {swapfc_path}...") try: for file in os.listdir(swapfc_path): force_remove(os.path.join(swapfc_path, file), verbose=True) except OSError: pass sem.remove()
def __init__(self, shm_key, lock_key, msg_size, queue_len): self.msg_size = msg_size self.queue_len = queue_len self.mem_size = HEAD_LEN + msg_size * queue_len self.mem = sysv_ipc.SharedMemory(shm_key, flags=sysv_ipc.IPC_CREAT, mode=0600, size=self.mem_size) assert self.mem_size == self.mem.size self.lock = sysv_ipc.Semaphore(lock_key, flags=sysv_ipc.IPC_CREAT, mode=0600, initial_value=1) self.lock.acquire() head_buff = self.mem.read(HEAD_LEN, offset=0) _mb, msg_bgn, msg_end, msg_cnt, _me = struct.unpack('!5I', head_buff) if (_mb, msg_bgn, msg_end, msg_cnt, _me) == (0, 0, 0, 0, 0): _mb = MAGIC_BGN _me = MAGIC_END head_buff = struct.pack('!5I', _mb, msg_bgn, msg_end, msg_cnt, _me) self.mem.write(head_buff, offset=0) print 'IPC_MsgQ: init bytes=%s' % self.mem_size self.lock.release() assert _mb == MAGIC_BGN assert _me == MAGIC_END
def getFrameCount(self): frameCount = "-1" if self.running == True: if self.memory == None: # Open shared memory object self.memory = sysv_ipc.SharedMemory(20130821) if self.semaphore == None: # Open semaphore self.semaphore = sysv_ipc.Semaphore(20130822) # Acquire the semaphore self.semaphore.acquire(2) # Read frame count from shared memory frameCount = self.memory.read() # Release the semaphore self.semaphore.release() # Find the 'end' of the string and strip i = frameCount.find('\0') if i != -1: frameCount = frameCount[:i] return frameCount
def __init__(self, key): try: self.sem = sysv_ipc.Semaphore(key) print "already exists" except sysv_ipc.ExistentialError: self.sem = sysv_ipc.Semaphore(key, sysv_ipc.IPC_CREAT, 0666, 1) print "created"
def __init__(self): try: self.sem = sysv_ipc.Semaphore(key_smartphone_ip_sem, sysv_ipc.IPC_CREX) except sysv_ipc.ExistentialError: # One of my peers created the semaphore already self.sem = sysv_ipc.Semaphore(key_smartphone_ip_sem) # Waiting for that peer to do the first acquire or release while not self.sem.o_time: time.sleep(.1) else: # Initializing sem.o_time to nonzero value self.sem.release() try: self.memory = sysv_ipc.SharedMemory(key_smartphone_ip_sm, sysv_ipc.IPC_CREX) except sysv_ipc.ExistentialError: self.memory = sysv_ipc.SharedMemory(key_smartphone_ip_sm)
def get_semaphore(): global GLOBAL_SEMAPHORE if GLOBAL_SEMAPHORE: return GLOBAL_SEMAPHORE try: semaphore = sysv_ipc.Semaphore(SEMAPHORE_KEY, sysv_ipc.IPC_CREX, mode=0666) except sysv_ipc.ExistentialError: semaphore = sysv_ipc.Semaphore(SEMAPHORE_KEY) while not semaphore.o_time: time.sleep(.1) else: semaphore.release() GLOBAL_SEMAPHORE = semaphore return GLOBAL_SEMAPHORE
def run(self): superblock.load_superblock(self.partition_name) self.load_bg_table() key = ipc.get_ipc_key(self.superblock) with open(self.keyfile, 'w+') as f: f.write('%d\n' % key) self.snd_sem = sysv_ipc.Semaphore(key, sysv_ipc.IPC_CREAT) self.rcv_sem = sysv_ipc.Semaphore(key + 1, sysv_ipc.IPC_CREAT) self.mq = sysv_ipc.MessageQueue(key, sysv_ipc.IPC_CREAT) while True: self.snd_sem.acquire() msg_buf, msg_type = self.mq.receive() self.handle_message(msg_buf, msg_type)
def main(): print('Python: ', __file__, ' PID: ', os.getpid()) signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGUSR1, signal_handler) semaphore = None while not semaphore: try: semaphore = sysv_ipc.Semaphore(SEM_KEY) except sysv_ipc.ExistentialError: print('Semaphore is not initialized, wait...') semaphore = None time.sleep(1) while True: semaphore.acquire() print('') print('Lock ', __file__, '...') sec_sleep = random.randint(1, 5) print('Sleep: ', sec_sleep) time.sleep(sec_sleep) semaphore.release() print('Unock ', __file__, '...') print('')
def __init__(self, nb_foyers=4): """Constructeur de notre classe""" #print("FIRST THING IN METEO") self.nb_foyers = nb_foyers self.date = 0 # int between 0 and 365 -> to get from Market self.conditions = [ self.weather_conditions() for _ in range(self.nb_foyers) ] # contient les facteurs pour le calcul de la tempé self.temperatures = [] try: self.sm = sysv_ipc.SharedMemory( 10) # on se connecte à la shared memory except sysv_ipc.ExistentialError: print("Méteo Cannot connect to shared Memory", 10, ", terminating NOW.") sys.exit(1) try: self.smSema = sysv_ipc.Semaphore(10) except sysv_ipc.ExistentialError: print("Méteo Cannot connect to semaphore", 10, ", terminating NOW.") sys.exit(1) self.current_temperature( ) # donne les températures actuelles pour les foyers self.setup()
def test_remove(self): """tests that sem.remove() works""" self.sem.remove() with self.assertRaises(sysv_ipc.ExistentialError): sysv_ipc.Semaphore(self.sem.key) # Wipe this out so that self.tearDown() doesn't crash. self.sem = None
def break_(self): try: lock = sysv_ipc.Semaphore(key=self.key) lock.remove() except sysv_ipc.ExistentialError: return False else: return True
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 sem = sysv_ipc.Semaphore(None, sysv_ipc.IPC_CREX) self.assertIsNotNone(sem.key) self.assertGreaterEqual(sem.key, sysv_ipc.KEY_MIN) self.assertLessEqual(sem.key, sysv_ipc.KEY_MAX) sem.remove()
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. sem = sysv_ipc.Semaphore(None, flags=sysv_ipc.IPC_CREX, mode=0x180, initial_value=0) sem.remove()
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 server_run(): memory_size = sysv_ipc.PAGE_SIZE * (1 << 9) mem = sysv_ipc.SharedMemory(1, sysv_ipc.IPC_CREX, size=memory_size) server_semaphore = sysv_ipc.Semaphore(2, sysv_ipc.IPC_CREX) client_semaphore = sysv_ipc.Semaphore(3, sysv_ipc.IPC_CREX) size = 1 << 20 data1 = b'a' * size data2 = b'b' * size duration = 1 # end = time.time() + duration # msgs = 0 while True: mem.write(data1) server_semaphore.release() client_semaphore.acquire() mem.write(data2) server_semaphore.release() client_semaphore.acquire()
def semaphore_remove(key): try: semaphore = sysv_ipc.Semaphore(key) except sysv_ipc.ExistentialError: if (verbose): print('''The semaphore with key "{}" doesn't exist.'''.format(key)) else: semaphore.remove() if (verbose): print('Removed the semaphore with key "{}".'.format(key))
def createStrand(self, StrandConstructor, tag, args): self.lock.acquire() semaphore = sysv_ipc.Semaphore(self.sem_key_next, sysv_ipc.IPC_CREX) strand = StrandConstructor(self, self.msgque_key, semaphore, self.sem_key_next, tag, args) self.sem_key_next = self.sem_key_next + 1 self.semaphore_list.append(semaphore) self.tag2strand[tag] = strand self.lock.release() return strand
def test_attribute_o_time(self): """exercise Semaphore.o_time""" sem = sysv_ipc.Semaphore(None, sysv_ipc.IPC_CREX) self.assertEqual(self.sem.o_time, 0) # sem.release() will set o_time. sem.release() # I can't know precisely when o_time was set, but there should be < 10 seconds between # the sem.release() line above and the assertion below. self.assertLess(time.time() - sem.o_time, 10) self.assertWriteToReadOnlyPropertyFails('o_time', 42) sem.remove()
def main(): utils.say("Oooo 'ello, I'm Mrs. Conclusion!") params = utils.read_params() semaphore = sysv_ipc.Semaphore(params["KEY"]) memory = sysv_ipc.SharedMemory(params["KEY"]) utils.say("memory attached at %d" % memory.address) what_i_wrote = "" s = "" for i in range(0, params["ITERATIONS"]): utils.say("i = %d" % i) if not params["LIVE_DANGEROUSLY"]: # Wait for Mrs. Premise to free up the semaphore. utils.say("acquiring the semaphore...") semaphore.acquire() s = utils.read_from_memory(memory) while s == what_i_wrote: if not params["LIVE_DANGEROUSLY"]: # Release the semaphore... utils.say("releasing the semaphore") semaphore.release() # ...and wait for it to become available again. utils.say("acquiring for the semaphore...") semaphore.acquire() s = utils.read_from_memory(memory) if what_i_wrote: if PY_MAJOR_VERSION > 2: what_i_wrote = what_i_wrote.encode() try: assert(s == hashlib.md5(what_i_wrote).hexdigest()) except AssertionError: raise AssertionError("Shared memory corruption after %d iterations." % i) if PY_MAJOR_VERSION > 2: s = s.encode() what_i_wrote = hashlib.md5(s).hexdigest() utils.write_to_memory(memory, what_i_wrote) if not params["LIVE_DANGEROUSLY"]: utils.say("releasing the semaphore") semaphore.release() # TODO: remove time.sleep(1)
def __init__(self, id): """ :param id: The data model identifier, e.g. 'conf.service.ftp.share'. """ # Create the data model object. self._model = openmediavault.config.Datamodel(id) # Get the path to the database. self._database_file = openmediavault.getenv("OMV_CONFIG_FILE") os.stat(self._database_file) # Get the property names that must be handled as lists/arrays. self._force_list = self._get_array_properties() # Set the default response value. self._response = None # The XML tree. self._root_element = None # Create the semaphore to control access to the database resource. try: self._semaphore = sysv_ipc.Semaphore(4815162342, sysv_ipc.IPC_CREX) except sysv_ipc.ExistentialError: # The semaphore already exists. self._semaphore = sysv_ipc.Semaphore(4815162342) else: self._semaphore.release()
def main(): print("DB_IPCHECKER: starting") try: memory = sysv_ipc.SharedMemory(key_smartphone_ip_sm, sysv_ipc.IPC_CREX) except sysv_ipc.ExistentialError: memory = sysv_ipc.SharedMemory(key_smartphone_ip_sm) try: sem = sysv_ipc.Semaphore(key_smartphone_ip_sem, sysv_ipc.IPC_CREX) except sysv_ipc.ExistentialError: # One of my peers created the semaphore already sem = sysv_ipc.Semaphore(key_smartphone_ip_sem) # Waiting for that peer to do the first acquire or release while not sem.o_time: time.sleep(.1) else: # Initializing sem.o_time to nonzero value sem.release() while (True): time.sleep(2) sem.acquire() memory.write(find_smartphone_ip()) sem.release()
def test_IPC_CREAT_new(self): """tests sysv_ipc.IPC_CREAT to create a new semaphore without IPC_EXCL""" # I can't pass None for the name unless I also pass IPC_EXCL. key = make_key() # Note: this method of finding an unused key is vulnerable to a race # condition. It's good enough for test, but don't copy it for use in # production code! key_is_available = False while not key_is_available: try: sem = sysv_ipc.Semaphore(key) sem.close() except sysv_ipc.ExistentialError: key_is_available = True else: key = make_key() sem = sysv_ipc.Semaphore(key, sysv_ipc.IPC_CREAT) self.assertIsNotNone(sem) sem.remove()