def __init__(self, timeout=2000, size=2**28): self.app = QCoreApplication.instance() if self.app is None: self.app = QCoreApplication([]) self.sock = QLocalSocket() self.sock.connectToServer("LivePlot") if not self.sock.waitForConnected(): raise EnvironmentError("Couldn't find LivePlotter instance") self.sock.disconnected.connect(self.disconnect_received) key = str(uuid.uuid4()) self.shared_mem = QSharedMemory(key) if not self.shared_mem.create(size): raise Exception("Couldn't create shared memory %s" % self.shared_mem.errorString()) logging.debug('Memory created with key %s and size %s' % (key, self.shared_mem.size())) self.sock.write(key.encode()) self.sock.waitForBytesWritten() self.is_connected = True self.timeout = timeout atexit.register(self.close)
def respond(self, byteArray, meta=None): if not self.conn: return False self.log("Sending Response. dataType: {0}, renderId: {1}".format( meta.get("dataType"), meta.get("renderId"))) obj = {"type": self.TYPE_RESPONSE, "meta": meta or {}} memKey = self.nextMemoryKey() obj["memoryKey"] = memKey # TODO: check that the memory segment is not used # store data in shared memory mem = QSharedMemory(memKey) if mem.isAttached(): mem.detach() if not mem.create(len(byteArray)): self.log(mem.errorString()) return False self.log("Shared memory created: {0}, {1} bytes".format( memKey, len(byteArray))) mem.lock() try: ctypes.memmove(int(mem.data()), byteArray, len(byteArray)) finally: mem.unlock() self._mem[memKey] = mem self.conn.write(json.dumps(obj).encode("utf-8") + b"\n") self.conn.flush() return True
def __init__(self, key='memory_condition_key'): self._shm = QSharedMemory(key) if not self._shm.attach(): if not self._shm.create(1): raise RuntimeError('error creating shared memory: %s' % self._shm.errorString()) self.condition = False
def is_already_running(self): """ Look to see if AppFTD is already running and ask if a 2nd instance is to be started. """ self.shared_memory = QSharedMemory('AppFTD') if self.shared_memory.attach(): log.error("It's already running") return True else: self.shared_memory.create(1) return False
def single_instance_lock(): sharedMemory = QSharedMemory( "77rWEV37vupNhQs6ktDREthqSciyV77OYrqPBSwV755JFIhl9iOywB7G5DkAKU8Y") if sharedMemory.attach(QSharedMemory.ReadOnly): sharedMemory.detach() return None if sharedMemory.create(1): return sharedMemory return None
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.shareMemory = QSharedMemory('QSharedMemoryExample') self.ui = MessageSender() self.setWindowTitle("simple communication demo") self.mainLayout = QVBoxLayout() self.mainLayout.addWidget(self.ui) self.setFixedSize(500, 600) self.setLayout(self.mainLayout)
def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.sharedMemory = QSharedMemory('QSharedMemoryExample') self.ui = Ui_Dialog() self.ui.setupUi(self) self.ui.loadFromFileButton.clicked.connect(self.loadFromFile) self.ui.loadFromSharedMemoryButton.clicked.connect(self.loadFromMemory) self.setWindowTitle("SharedMemory Example")
def single_instance_lock(currency): key = hashlib.sha256(currency.encode('utf-8') + "77rWEV37vupNhQs6ktDREthqSciyV77OYrqPBSwV755JFIhl9iOywB7G5DkAKU8Y".encode('utf-8'))\ .hexdigest() sharedMemory = QSharedMemory(key) if sharedMemory.attach(QSharedMemory.ReadOnly): sharedMemory.detach() return None if sharedMemory.create(1): return sharedMemory return None
def __init__(self, argv, key): super().__init__(argv) QSharedMemory(key).attach() self._memory = QSharedMemory(self) self._memory.setKey(key) if self._memory.attach(): self._running = True else: self._running = False if not self._memory.create(1): raise RuntimeError(self._memory.errorString()) self._key = key self._timeout = 1000 self._server = QLocalServer(self) if not self.isRunning(): self._server.newConnection.connect(self.handleMessage) self._server.listen(self._key) self._settings = QSettings("Raul Sangonzalo", "Musician Suite") # self._settings.setValue("currentDatabase", None) # testing purposes self.initialPrompt = InitialPrompt() self.initialPrompt.databaseSelected.connect(self.reloadInit)
def accept(self): logging.debug('connection accepted') conn = self.server.nextPendingConnection() conn.waitForReadyRead() key = str(conn.read(36).decode()) memory = QSharedMemory() memory.setKey(key) memory.attach() logging.debug('attached to memory %s with size %s'%(key, memory.size())) atexit.register(memory.detach) self.conns.append(conn) self.shared_mems.append(memory) conn.readyRead.connect(lambda: self.read_from(conn, memory)) conn.disconnected.connect(memory.detach) conn.write(b'ok')
def __init__(self, parent=None): super(ProducerDialog, self).__init__(parent) self.ui = Ui_Dialog() self.ui.setupUi(self) # We only allow one image to be put into the shared memory (otherwise we would need to # create a dedicated data structure within the SHARED memory and access it from Python and # C++ appropriately). Also note that "Open" and "Create" have very different semantics (see # docs) and we use "Create" to always create a "fresh" semaphore to not cause undesired # blocking/stalls, see also https://doc.qt.io/qt-5/qsystemsemaphore.html if CONSUMER == 0: self.ui.loadFromFileButton.clicked.connect(self.load_from_file) self.ui.loadFromSharedMemoryButton.setEnabled(False) self.setWindowTitle("Shared Memory Producer: Python Example") from prodcon_ipc.producer_ipc import ProducerIPC self.producer_ipc = ProducerIPC(UNIQUE_SHARED_MEMORY_NAME, SHARED_MEMORY_KEY_FILE) else: self.ui.loadFromSharedMemoryButton.clicked.connect( self.load_from_memory) self.ui.loadFromFileButton.setEnabled(False) self.setWindowTitle("Shared Memory Consumer: Python Example") from prodcon_ipc.consumer_ipc import ConsumerIPC self.consumer_ipc = ConsumerIPC(UNIQUE_SHARED_MEMORY_NAME, SHARED_MEMORY_KEY_FILE) if SHARED_STRUCT == 1: self.shmem_config = QSharedMemory('shared_struct_test') if self.shmem_config.isAttached() or self.shmem_config.attach(): if self.shmem_config.lock(): counter, stop_flag, file_name = struct.unpack( STRUCT_FORMAT, self.shmem_config.constData()) logzero.logger.debug( "Shared memory struct read: counter=" + str(counter) + ", stop_flag=" + str(stop_flag) + ", file_name=" + file_name) self.shmem_config.unlock() else: logzero.logger.error("unable to lock " + self.shmem_config.key()) # Note: if both processes detach from the memory, it gets deleted so that attach() fails. That's why we # simply never detach (HERE). Depending on the app design, there may be a better solution. #self.shmem_config.detach() else: logzero.logger.error("unable to attach " + self.shmem_config.key())
def instance_check(app): app.instance_check = QSharedMemory(f'{APP_NAME} - Instance Check') if not app.instance_check.create(4, QSharedMemory.ReadWrite): # Already running. Read the PID from the shared memory and return it. app.instance_check.attach(QSharedMemory.ReadOnly) app.instance_check.lock() view = memoryview(app.instance_check.data()) existing_pid = struct.unpack('=i', view[:4])[0] app.instance_check.unlock() return existing_pid # Write the current PID into the shared memory object. pid = app.applicationPid() app.instance_check.lock() app.instance_check.data()[:4] = memoryview(struct.pack('=i', pid)) app.instance_check.unlock() return 0
def __init__(self, *args, **kwargs): super(SharedApplication, self).__init__(*args, **kwargs) self._running = False key = "SharedApplication" + __version__ self._memory = QSharedMemory(key, self) isAttached = self._memory.isAttached() print("isAttached", isAttached) if isAttached: # 如果进程附加在共享内存上 detach = self._memory.detach() # 取消进程附加在共享内存上 print("detach", detach) if self._memory.create( 1) and self._memory.error() != QSharedMemory.AlreadyExists: # 创建共享内存,如果创建失败,则说明已经创建,否则未创建 print("create ok") else: print("create failed") self._running = True del self._memory
def receiveMessage(self): stream = QTextStream(self.conn) if stream.atEnd(): return data = stream.readAll() for json_str in data.split("\n")[:-1]: obj = json.loads(json_str) msgType = obj["type"] if msgType == self.TYPE_NOTIFICATION: self.log("Notification Received. code: {0}".format( obj["params"].get("code"))) if obj["params"].get("code") == self.N_DATA_RECEIVED: memKey = obj["params"]["memoryKey"] mem = self._mem[memKey] if mem.isAttached(): mem.detach() self.log( "Shared memory detached: key={0}".format(memKey)) del self._mem[memKey] else: self.notified.emit(obj["params"]) elif msgType == self.TYPE_REQUEST: self.log( "Request Received. dataType: {0}, renderId: {1}".format( obj["params"].get("dataType"), obj["params"].get("renderId"))) self.requestReceived.emit(obj["params"]) elif msgType == self.TYPE_RESPONSE: self.log( "Response Received. dataType: {0}, renderId: {1}".format( obj["meta"].get("dataType"), obj["meta"].get("renderId"))) mem = QSharedMemory(obj["memoryKey"]) if not mem.attach(QSharedMemory.ReadOnly): self.log( "Cannot attach this process to the shared memory segment: {0}" .format(mem.errorString())) return size = mem.size() self.log("Size of memory segment is {0} bytes.".format(size)) mem.lock() ba = QByteArray() buffer = QBuffer(ba) buffer.setData(mem.constData()) mem.unlock() mem.detach() data = ba.data() lines = data.split(b"\n") for line in lines[:5]: self.log(line[:76]) if len(lines) > 5: self.log("--Total {0} Lines Received--".format(len(lines))) self.notify({ "code": self.N_DATA_RECEIVED, "memoryKey": obj["memoryKey"] }) self.responseReceived.emit(data, obj["meta"])
# from tensorflow.keras.applications import ResNet50 # from tensorflow.keras.preprocessing import image # from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions SIZE = 224 CHANNELS = 3 #model = ResNet50(weights="imagenet") from PyQt5.QtCore import QSharedMemory,QBuffer import numpy as np from matplotlib import pyplot as plt import cv2 mem = QSharedMemory("image4") mem.attach() while True: mem.lock() t = np.array(mem.constData().asarray()) n_t = t[0:SIZE*SIZE*CHANNELS] plt.imshow(n_t.reshape((SIZE,SIZE,-1))) cv2.imwrite("test123.png",n_t.reshape((SIZE,SIZE,-1))) mem.unlock() break mem.unlock(); mem.detach(); #del model
for tunnel in self.tunnels: name = tunnel.name.text() data[name] = tunnel.tunnelconfig.as_dict() timestamp = int(time.time()) shutil.copy(CONF_FILE, F"{CONF_FILE}-{timestamp}") with open(CONF_FILE, "w") as fp: yaml.dump(data, fp) backup_configs = glob.glob(F"{CONF_FILE}-*") if len(backup_configs) > 10: for config in sorted(backup_configs, reverse=True)[10:]: os.remove(config) event.accept() if __name__ == '__main__': app = QApplication(sys.argv) sm = QSharedMemory("3866273d-f4d5-4bf3-b27b-772ca7915a61") if not sm.create(1): mb = QMessageBox() mb.setIcon(QMessageBox.Information) mb.setText("SSH Tunnel Manager is already running") mb.setWindowTitle("Oops!") mb.setStandardButtons(QMessageBox.Ok) mb.show() else: tm = TunnelManager() sys.exit(app.exec_())