QDataStream &operator<<(QDataStream &out, const ValuesChangedCommand &command) { static const bool dontUseSharedMemory = !qgetenv("DESIGNER_DONT_USE_SHARED_MEMORY").isEmpty(); if (!dontUseSharedMemory && command.valueChanges().count() > 5) { static quint32 keyCounter = 0; ++keyCounter; command.m_keyNumber = keyCounter; QByteArray outDataStreamByteArray; QDataStream temporaryOutDataStream(&outDataStreamByteArray, QIODevice::WriteOnly); temporaryOutDataStream.setVersion(QDataStream::Qt_4_8); temporaryOutDataStream << command.valueChanges();; QSharedMemory *sharedMemory = createSharedMemory(keyCounter, outDataStreamByteArray.size()); if (sharedMemory) { std::memcpy(sharedMemory->data(), outDataStreamByteArray.constData(), sharedMemory->size()); out << command.keyNumber(); return out; } } out << qint32(0); out << command.valueChanges(); return out; }
int main(int argc, char *argv[]) { QApplication a(argc, argv); a.setOrganizationName(APP_ORG); a.setApplicationVersion(APP_VERSION); a.setApplicationName(APP_NAME); QTranslator translator; const QStringList localeDirs({QString("%1/languages").arg(QDir::currentPath()), QString(qApp->applicationDirPath() + "/languages"), QString("/usr/share/%1/languages").arg(APP_NAME), QString("/usr/local/share/%1/languages").arg(APP_NAME), QString(QDir::home().absolutePath() + "/.local/share/%1/languages").arg(APP_NAME), QString(QDir::currentPath().left(QDir::currentPath().lastIndexOf("/")) + "/share/%1/languages").arg(APP_NAME)}); const QString langFile(qApp->applicationName()); foreach(const QString &dir, localeDirs){ if (translator.load(QLocale::system(),langFile, "_", dir )) { qApp->installTranslator(&translator); break; } } QApplication::setQuitOnLastWindowClosed(false); PopupWindow w; w.hide(); QSharedMemory sharedMemory; sharedMemory.setKey("QtAlsaVolume"); if (sharedMemory.attach()) { return 0; } if (!sharedMemory.create(1)) { return 0; } else{ return a.exec(); } }
int main(int argc, char *argv[]) { MainApp a(argc,argv); // had to disable this for now on Mac, // weird crash deep in Qt leaves shared memory segment dangling #ifdef Q_OS_WIN // http://qt-project.org/doc/qt-5/qtcore-sharedmemory-example.html // http://qt-project.org/forums/viewthread/18262/#89444 sharedMemory.setKey("Blink1ControlShMemKey"); if( !sharedMemory.create(1) ) { qDebug() << "Blink1Control already running"; QMessageBox::about(0, QString("Blink1Control running"), "Blink1Control is already running."); #ifdef Q_OS_WIN a.processEvents(); // FIXME: why are different OSes different here? return -1; #else return a.exec(); #endif } #endif MainWindow w; // this seems messed up, why even use mainwindow? // to capture power change (sleep/wake) on Windows // (can we move this to osFixes?) a.installNativeEventFilter(&w); return a.exec(); }
static PyObject *meth_QSharedMemory_setKey(PyObject *sipSelf, PyObject *sipArgs) { PyObject *sipParseErr = NULL; { const QString * a0; int a0State = 0; QSharedMemory *sipCpp; if (sipParseArgs(&sipParseErr, sipArgs, "BJ1", &sipSelf, sipType_QSharedMemory, &sipCpp, sipType_QString,&a0, &a0State)) { Py_BEGIN_ALLOW_THREADS sipCpp->setKey(*a0); Py_END_ALLOW_THREADS sipReleaseType(const_cast<QString *>(a0),sipType_QString,a0State); Py_INCREF(Py_None); return Py_None; } } /* Raise an exception if the arguments couldn't be parsed. */ sipNoMethod(sipParseErr, sipName_QSharedMemory, sipName_setKey, NULL); return NULL; }
/** Перезагружает словарь по пути changedDictionaryPath */ void DictionaryManager::reloadDictionary() { QString &path = changedDictionaryPath; qDebug() << QString("reloading dictionary from %1.").arg(path); try { QString key = filenameToKey.value(path); QSharedMemory *shared = data.value(key); if (!shared) throw Exception(QString("Ошибка перезагрузки словаря %1. Словарь не был загружен ранее.").arg(path)); QFile fileDictionary(path); QByteArray buffer; if (!fileDictionary.open(QFile::ReadOnly)) throw Exception(QString("Ошибка чтения файла словаря. Key: %1; file: %2").arg(key).arg(path)); buffer = fileDictionary.readAll(); shared->lock(); char *to = (char *)shared->data(); const char *from = buffer.data(); memcpy(to, from, qMin(shared->size(), buffer.size())); shared->unlock(); qDebug() << "Словарь обновлён"; } catch (Exception &ex) { qDebug() << tr("Ошибка во время загрузки словаря %1.\nОписание: %2").arg(path).arg(ex.text()); } }
int readonly_segfault() { QSharedMemory sharedMemory; sharedMemory.setKey("readonly_segfault"); sharedMemory.create(1024, QSharedMemory::ReadOnly); sharedMemory.lock(); set(sharedMemory, 0, 'a'); sharedMemory.unlock(); return EXIT_SUCCESS; }
/** * @brief Executed when new instance connect command is sent to LocalServer */ void Rshare::slotConnectionEstablished() { QLocalSocket *socket = localServer->nextPendingConnection(); socket->close(); delete socket; QSharedMemory newArgs; newArgs.setKey(QString(TARGET) + "_newArgs"); if (!newArgs.attach()) { std::cerr << "(EE) Rshare::slotConnectionEstablished() Unable to attach to shared memory segment." << newArgs.errorString().toStdString() << std::endl; return; } QBuffer buffer; QDataStream in(&buffer); QStringList args; newArgs.lock(); buffer.setData((char*)newArgs.constData(), newArgs.size()); buffer.open(QBuffer::ReadOnly); in >> args; newArgs.unlock(); newArgs.detach(); emit newArgsReceived(args); while (!args.empty()) { std::cerr << "Rshare::slotConnectionEstablished args:" << QString(args.takeFirst()).toStdString() << std::endl; } }
void conflict_core::openAida(){ aida.setKey("AIDA64_SensorValues"); if (aida.isAttached()){ aida.detach(); } if (!aida.create(10000)){ conflict.aidaOpen = false; }else{ conflict.aidaOpen = true; } }
/*! Destructor */ TasDataShare::~TasDataShare() { QMutableHashIterator<QString, QSharedMemory*> i(mStoredDataBlocks); while (i.hasNext()) { i.next(); QSharedMemory* mem = i.value(); mem->detach(); delete mem; } mStoredDataBlocks.clear(); }
bool isRunning(){ if(!appShare.create(16)){ if(!appShare.attach() || !appShare.lock()) return false; void* data = appShare.data(); snprintf((char*)data, 16, "Open"); appShare.unlock(); return true; } return false; }
void MainWindow::timerTick(){ // Check if another instance requested this in the foreground if(appShare.lock()){ void* data = appShare.data(); if((QString)QByteArray((const char*)data) == "Open") show(); // Remove the request *(char*)data = 0; appShare.unlock(); } scanKeyboards(); }
void conflict_core::updateAida(){ QBuffer buffer; QDataStream in(&buffer); QString text; if(conflict.aidaOpen){ aida.lock(); buffer.setData((char*)aida.constData(), aida.size()); buffer.open(QBuffer::ReadOnly); in >> text; ui->debugOutputOut->append(text); aida.unlock(); }
bool TasDataShare::detachSharedData(const QString& identifier) { if(mStoredDataBlocks.contains(identifier)){ QSharedMemory* mem = mStoredDataBlocks.value(identifier); if(!mem->detach()){ return false; } delete mem; mem = 0; mStoredDataBlocks.remove(identifier); } return true; }
int SingleApp(){//TODO:problem. int ret = 1; QSharedMemory sharedMemory; sharedMemory.setKey("FishProjectApp"); // if (sharedMemory.create(1) && sharedMemory.error() != QSharedMemory::AlreadyExists) if(sharedMemory.attach()) { qDebug()<<"single"; return 0; } sharedMemory.create(1); qDebug()<<"create"; return ret; }
void *COMPRESSOR_create_ladspa(const char *key){ QSharedMemory *shared = new QSharedMemory(key); if(shared->attach()==false){ fprintf(stderr,"Ladspa compressor: Couldn't attach... Error: %s\n",shared->error()==QSharedMemory::NoError?"No error (?)":shared->errorString().toAscii().data()); exit(0); } mydsp *dsp = (mydsp*)shared->data(); fprintf(stderr,"dsp: %p.\n",dsp); portData* port_data = new portData(dsp->mydsp::getNumInputs(), dsp->mydsp::getNumOutputs()); dsp->mydsp::buildUserInterface(port_data); // buildUserInterface is called twice on the dsp data. One time in each process. return new PLUGIN(0, port_data, dsp); }
int main(int argc, char *argv[]) { qRegisterMetaTypeStreamOperators<SQProfile>("SQProfile"); QApplication a(argc, argv); signal(SIGINT, onSIGINT_TERM); signal(SIGTERM, onSIGINT_TERM); a.setApplicationName(QString("shadowsocks-qt5")); a.setApplicationDisplayName(QString("Shadowsocks-Qt5")); a.setApplicationVersion(APP_VERSION); #ifdef Q_OS_WIN if (QLocale::system().country() == QLocale::China) { a.setFont(QFont("Microsoft Yahei", 9, QFont::Normal, false)); } else { a.setFont(QFont("Segoe UI", 9, QFont::Normal, false)); } QIcon::setThemeName("Breeze"); #endif QTranslator ssqt5t; ssqt5t.load(QLocale::system(), "ss-qt5", "_", ":/i18n"); a.installTranslator(&ssqt5t); MainWindow w; QSharedMemory sharedMem; sharedMem.setKey("Shadowsocks-Qt5"); if (w.isOnlyOneInstance()) { if (!sharedMem.create(1)) { QMessageBox::critical(&w, QObject::tr("Error"), QObject::tr("Another instance of Shadowsocks-Qt5 is already running.")); return -1; } } w.show(); if (w.isHideWindowOnStartup()) { if (w.isUsingAppIndicator()) { QTimer::singleShot(5, &w, SLOT(minimizeToSysTray())); } else { w.minimizeToSysTray(); } } return a.exec(); }
int main(int argc, char *argv[]) { QApplication a(argc, argv); QCoreApplication::setOrganizationName("Scary HalloSoft"); QCoreApplication::setOrganizationDomain("hallosoft.de"); QCoreApplication::setApplicationName("Hallos Inspection Tool"); // Version QString versionString = QString("%1.%2.%3.%4").arg(VERSION_MAJOR).arg(VERSION_MINOR).arg(VERSION_REVISION).arg(VERSION_BUILD); a.setApplicationVersion(versionString); qDebug() << "Version" << versionString; // splash screen QPixmap splashPixmap(":/pic/icons/Slpash.png"); Q_ASSERT(!splashPixmap.isNull()); QSharedMemory sharedMemory; sharedMemory.setKey("HallosInspectionTool"); if (!sharedMemory.create(1)) { qDebug() << "Shared memory:" << sharedMemory.errorString(); QMessageBox::warning(0, QApplication::tr("Warning!"), QApplication::tr("An instance of HIT is running!") ); exit(0); // Exit, a process is already running } QSplashScreen splash(splashPixmap); splash.show(); qApp->processEvents(); splash.showMessage(QString("Version %1").arg(versionString), Qt::AlignBottom); qApp->processEvents(); MainWindow w; w.show(); splash.finish(&w); return a.exec(); }
void *COMPRESSOR_create_shared(float sample_rate){ QString key = "radium_crashreporter_" + QString::number(QDateTime::currentMSecsSinceEpoch()); QSharedMemory *shared = new QSharedMemory(key); if(shared->create(sizeof(Compressor_wrapper))==false){ fprintf(stderr,"COMPRESSOR_create_shared: Couldn't create... Error: %s\n",shared->error()==QSharedMemory::NoError?"No error (?)":shared->errorString().toAscii().data()); return NULL; } void *memory = shared->data(); Compressor_wrapper *wrapper = new(memory) Compressor_wrapper(sample_rate); printf("memory: %p, shared: %p\n",memory,shared); wrapper->key = key; wrapper->shared = shared; return wrapper; }
static PyObject *meth_QSharedMemory_key(PyObject *sipSelf, PyObject *sipArgs) { PyObject *sipParseErr = NULL; { QSharedMemory *sipCpp; if (sipParseArgs(&sipParseErr, sipArgs, "B", &sipSelf, sipType_QSharedMemory, &sipCpp)) { QString *sipRes; Py_BEGIN_ALLOW_THREADS sipRes = new QString(sipCpp->key()); Py_END_ALLOW_THREADS return sipConvertFromNewType(sipRes,sipType_QString,NULL); } }
static mydsp *create_shared_dsp(){ QString key = "radium_crashreporter_" + QString::number(QDateTime::currentMSecsSinceEpoch()); QSharedMemory *shared = new QSharedMemory(key); if(shared->create(sizeof(mydsp))==false){ fprintf(stderr,"COMPRESSOR_create_shared: Couldn't create... Error: %s\n",shared->error()==QSharedMemory::NoError?"No error (?)":shared->errorString().toAscii().data()); return NULL; } void *memory = shared->data(); mydsp *dsp = new(memory) mydsp(); #if 0 printf("memory: %p, shared: %p\n",memory,shared); dsp->key = key; dsp->shared = shared; #endif //printf("system: %d\n",system(QString(QString("xterm -e gdb /home/kjetil/radium_compressor/radium_compressor --args --ladspa-slave ")+key).toAscii())); printf("system: %d\n",system(QString(QString("xterm -e gdb --args /home/kjetil/radium_compressor/radium_compressor --ladspa-slave ")+key+" &").toAscii())); return dsp; #if 0 if(fork()!=0){ return dsp; }else{ QSharedMemory *shared = new QSharedMemory(key); if(shared->attach()==false){ fprintf(stderr,"Ladspa compressor: Couldn't attach... Error: %s\n",shared->error()==QSharedMemory::NoError?"No error (?)":shared->errorString().toAscii().data()); exit(0); } char *argv[1]={(char*)"radium_compressor"}; mydsp *dsp = (mydsp*)shared->data(); fprintf(stderr,"dsp: %p.\n",dsp); portData* port_data = new portData(dsp->getNumInputs(), dsp->getNumOutputs()); dsp->buildUserInterface(port_data); // This is the second time buildUserInterface is called twice on the dsp data. One time in each process. start_program(1,argv,new PLUGIN(0, port_data, dsp)); exit(0); return NULL; } #endif }
void setString(const char value[], QString name) { QSharedMemory* sharedMemory = stringMemoryMap.value(name); if(sharedMemory->isAttached()) sharedMemory->detach(); int size = strlen(value) + sizeof(char); if (!sharedMemory->create(size)) { if (!sharedMemory->isAttached()) { sharedMemory->attach(QSharedMemory::ReadWrite); } } sharedMemory->lock(); char *to = (char*)sharedMemory->data(); memcpy(to, value, qMin(sharedMemory->size(), size)); sharedMemory->unlock(); }
void setInt(int value, QString name) { QSharedMemory* sharedMemory = intMemoryMap.value(name); if(sharedMemory->isAttached()) sharedMemory->detach(); int size = sizeof(int); if (!sharedMemory->create(size)) { if (!sharedMemory->isAttached()) { sharedMemory->attach(QSharedMemory::ReadWrite); } } sharedMemory->lock(); int* to = (int*)sharedMemory->data(); memcpy(to, &value, qMin(sharedMemory->size(), size)); sharedMemory->unlock(); }
void setBool(bool value, QString name) { QSharedMemory* sharedMemory = boolMemoryMap.value(name); if(sharedMemory->isAttached()) { sharedMemory->detach(); } int size = sizeof(bool); if (!sharedMemory->create(size)) { sharedMemory->attach(QSharedMemory::ReadWrite); } sharedMemory->lock(); bool *array = (bool*)sharedMemory->data(); memcpy(array, &value, qMin(sharedMemory->size(), size)); sharedMemory->unlock(); }
bool TasDataShare::storeSharedData(const QString& identifier, const TasSharedData& data, QString& errMsg) { QSharedMemory* storage = new QSharedMemory(identifier); QByteArray array = data.asArray(); int size = array.size(); if(!storage->create(size)){ delete storage; return false; } storage->lock(); char *to = (char*)storage->data(); const char *from = array.data(); memcpy(to, from, qMin(storage->size(), size)); storage->unlock(); mStoredDataBlocks.insert(identifier, storage); errMsg = " key:" + storage->key(); return true; }
// Example how to get json using shared memory. Not tested :-D std::pair<bool, QString> json() { QSharedMemory sharedMemory; if (!sharedMemory.attach()) { return std::make_pair<bool, QString>(false, QString()); } QBuffer buffer; QDataStream in(&buffer); QString json; sharedMemory.lock(); buffer.setData((char*)sharedMemory.constData(), sharedMemory.size()); buffer.open(QBuffer::ReadOnly); in >> json; sharedMemory.unlock(); sharedMemory.detach(); return std::make_pair<bool, QString>(false, QString()); }
int getInt(QString name) { QSharedMemory* sharedMemory = intMemoryMap[name]; sharedMemory->attach(QSharedMemory::ReadOnly); int returnValue = 0; if(!sharedMemory->isAttached()) { return returnValue; } sharedMemory->lock(); int* value = (int*)sharedMemory->data(); memcpy(&returnValue, value, sizeof(value)); sharedMemory->unlock(); sharedMemory->detach(); return returnValue; }
static QSharedMemory *createSharedMemory(qint32 key, int byteCount) { QSharedMemory *sharedMemory = new QSharedMemory(QString(valueKeyTemplateString).arg(key)); bool sharedMemoryIsCreated = sharedMemory->create(byteCount); if (!sharedMemoryIsCreated) { if (sharedMemory->isAttached()) sharedMemory->attach(); sharedMemory->detach(); sharedMemoryIsCreated = sharedMemory->create(byteCount); } if (sharedMemoryIsCreated) { globalSharedMemoryCache.insert(key, sharedMemory); return sharedMemory; } return 0; }
/*! Загружает словарь из файла filename в разделяемую память с ключём key. */ QSharedMemory *DictionaryManager::loadDictionary(const QString &filename, const QString &key) { QFile fileDictionary(filename); QByteArray buffer; QSharedMemory *shared; if (!fileDictionary.open(QFile::ReadOnly)) throw Exception(QString("Ошибка чтения файла словаря. Key: %1; file: %2").arg(key).arg(filename)); buffer = fileDictionary.readAll(); shared = new QSharedMemory(key); if (!shared->create(buffer.size() * 1.2)) // Выделяем память с 20% запасом throw Exception(QString("Ошибка выделения памяти под словарь %1. Описание: %2. " "Словарь будет пропущен.") .arg(key) .arg(shared->errorString())); shared->lock(); char *to = (char *)shared->data(); const char *from = buffer.data(); memcpy(to, from, qMin(shared->size(), buffer.size())); shared->unlock(); return shared; }
char* getString(QString name) { QSharedMemory* sharedMemory = stringMemoryMap[name]; sharedMemory->attach(QSharedMemory::ReadOnly); char* strValue = (char*)""; if(!sharedMemory->isAttached()) { return strValue; } sharedMemory->lock(); char* shared = (char*)sharedMemory->data(); strValue = new char[strlen(shared) + sizeof(char)]; strcpy(strValue, shared); sharedMemory->unlock(); sharedMemory->detach(); return strValue; }
bool getBool(QString name) { QSharedMemory* sharedMemory = boolMemoryMap[name]; sharedMemory->attach(QSharedMemory::ReadOnly); bool returnValue = false; if(!sharedMemory->isAttached()) { return returnValue; } sharedMemory->lock(); bool value = *(bool*)sharedMemory->data(); returnValue = value; sharedMemory->unlock(); sharedMemory->detach(); return returnValue; }