int main(int argc, char *argv[]) { QApplication a(argc, argv); QSharedMemory sharedMemory("docmaq"); if (sharedMemory.create(1) && sharedMemory.error() != QSharedMemory::AlreadyExists) { // Check if Configure is already running QSharedMemory sm("d_configure"); if(sm.create(1) && sm.error() != QSharedMemory::AlreadyExists) { sharedMemory.detach(); a.addLibraryPath("./plugins"); GetConfig get; return a.exec(); } else { QMessageBox::critical(0,"DocmaQ Configure Error", " DocmaQ Configure is already running." ); return 0; } } else { QMessageBox::critical(0,"DocmaQ Configure Error ","DocmaQ is running. Please Close it first to open DocmaQ Configure."); return 0; } }
PassRefPtr<SharedMemory> SharedMemory::createFromVMBuffer(void* data, size_t size) { ASSERT(size); // Create a Mach port that represents the shared memory. mach_port_t port; memory_object_size_t memoryObjectSize = round_page(size); kern_return_t kr = mach_make_memory_entry_64(mach_task_self(), &memoryObjectSize, toVMAddress(data), VM_PROT_DEFAULT | VM_PROT_IS_MASK, &port, MACH_PORT_NULL); if (kr != KERN_SUCCESS) { LOG_ERROR("Failed to create a mach port for shared memory. %s (%x)", mach_error_string(kr), kr); return 0; } ASSERT(memoryObjectSize >= round_page(size)); if (memoryObjectSize < round_page(size)) { mach_port_deallocate(mach_task_self(), port); return 0; } RefPtr<SharedMemory> sharedMemory(adoptRef(new SharedMemory)); sharedMemory->m_size = size; sharedMemory->m_data = data; sharedMemory->m_shouldVMDeallocateData = false; sharedMemory->m_port = port; return sharedMemory.release(); }
PassRefPtr<SharedMemory> SharedMemory::create(size_t size) { ASSERT(size); mach_vm_address_t address; kern_return_t kr = mach_vm_allocate(mach_task_self(), &address, round_page(size), VM_FLAGS_ANYWHERE); if (kr != KERN_SUCCESS) { LOG_ERROR("Failed to allocate mach_vm_allocate shared memory (%zu bytes). %s (%x)", size, mach_error_string(kr), kr); return 0; } // Create a Mach port that represents the shared memory. mach_port_t port; memory_object_size_t memoryObjectSize = round_page(size); kr = mach_make_memory_entry_64(mach_task_self(), &memoryObjectSize, address, VM_PROT_DEFAULT, &port, MACH_PORT_NULL); if (kr != KERN_SUCCESS) { LOG_ERROR("Failed to create a mach port for shared memory. %s (%x)", mach_error_string(kr), kr); mach_vm_deallocate(mach_task_self(), address, round_page(size)); return 0; } ASSERT(memoryObjectSize >= round_page(size)); RefPtr<SharedMemory> sharedMemory(adoptRef(new SharedMemory)); sharedMemory->m_size = size; sharedMemory->m_data = toPointer(address); sharedMemory->m_port = port; return sharedMemory.release(); }
void readSharedMemory(qint32 key, QVector<PropertyValueContainer> *valueChangeVector) { QSharedMemory sharedMemory(QString(valueKeyTemplateString).arg(key)); bool canAttach = sharedMemory.attach(QSharedMemory::ReadOnly); if (canAttach) { QDataStream in(QByteArray::fromRawData(static_cast<const char*>(sharedMemory.constData()), sharedMemory.size())); in.setVersion(QDataStream::Qt_4_8); in >> *valueChangeVector; } }
int main(int argc, char *argv[]) { QSharedMemory sharedMemory("FilePirateClient"); if (!sharedMemory.create(1) || sharedMemory.error() == QSharedMemory::AlreadyExists) return 0; #ifndef QT_DEBUG QString fileName = FilePirate::StoragePath + "captains-log.log"; QFile *log = new QFile(fileName); if (log->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) { out = new QTextStream(log); qInstallMsgHandler(logOutput); } else { qDebug() << "Error opening log file '" << fileName << "'. All debug output redirected to console."; } #endif QApplication a(argc, argv); QPixmap pixmap(":/images/splash.png"); QSplashScreen *splash = new QSplashScreen(pixmap); splash->show(); a.processEvents(); splash->showMessage("Loading...",Qt::AlignCenter | Qt::AlignBottom,Qt::white); qDebug() << "Registering URL handler..."; QDesktopServices::setUrlHandler("pirate",&FilePirate::Application(),"handleUrl"); a.processEvents(); // Force the user to see the splash screen for at least some time QMutex dummy; dummy.lock(); QWaitCondition wait; wait.wait(&dummy, 750); dummy.unlock(); // And move on to the rest of loading splash->showMessage("Loading settings...",Qt::AlignCenter | Qt::AlignBottom,Qt::white); // load the settings here FilePirate::Application().settingsLoaded = FilePirate::Application().loadSettings(); splash->showMessage("Loading local filelist...",Qt::AlignCenter | Qt::AlignBottom,Qt::white); FilePirate::Application().fileMon->fullRefreshFileList(); // bring up the filelist - this is a good time to start up the settings dialog // if the user hasn't done so yet... splash->showMessage("Finishing up...",Qt::AlignCenter | Qt::AlignBottom,Qt::white); FilePirate::Application().moveHelpersToThreads(); MainWindow w; w.show(); splash->finish(&w); delete splash; return a.exec(); }
PassRefPtr<SharedMemory> SharedMemory::create(size_t size) { mach_vm_address_t address; kern_return_t kr = mach_vm_allocate(mach_task_self(), &address, round_page(size), VM_FLAGS_ANYWHERE); if (kr != KERN_SUCCESS) return 0; RefPtr<SharedMemory> sharedMemory(adoptRef(new SharedMemory)); sharedMemory->m_size = size; sharedMemory->m_data = toPointer(address); return sharedMemory.release(); }
/** * The primesieve GUI is launched if the user starts the application * by mouse click or without arguments, a PrimeSieveProcess is * launched if process and a shared memory identifiers are provided as * arguments. * @param argv[1] [process identifier] * @param argv[2] [Shared memory identifier] * @see PrimeSieveProcess.cpp */ int main(int argc, char *argv[]) { if (argc == 3) { QString psp("PrimeSieveProcess"); QString parent(argv[1]); if (parent.compare(psp) == 0) { // open an existing and initialized shared memory QString id(argv[2]); QSharedMemory sharedMemory(id); if (!sharedMemory.attach()) { std::cerr << "Unable to attach shared memory " << argv[2] << std::endl; exit(EXIT_FAILURE); } // map the attached shared memory to the shm segment primesieve::ParallelPrimeSieve::SharedMemory* shm = static_cast<primesieve::ParallelPrimeSieve::SharedMemory*>(sharedMemory.data()); try { // initialize the ParallelPrimeSieve object with // values from the shared memory segment provided by // the primesieve GUI and start sieving if (!shm) throw std::runtime_error("sharedMemory.data() must not be NULL"); primesieve::ParallelPrimeSieve pps; pps.init(*shm); pps.sieve(); } catch (std::exception& e) { sharedMemory.detach(); std::cerr << "ParallelPrimeSieve error: " << e.what() << std::endl; exit(EXIT_FAILURE); } sharedMemory.detach(); return 0; } } // Qt GUI interface QApplication a(argc, argv); PrimeSieveGUI w; w.show(); return a.exec(); }
PassRefPtr<SharedMemory> SharedMemory::create(const Handle& handle, Protection protection) { if (handle.isNull()) return 0; // Map the memory. vm_prot_t vmProtection = machProtection(protection); mach_vm_address_t mappedAddress = 0; kern_return_t kr = mach_vm_map(mach_task_self(), &mappedAddress, handle.m_size, 0, VM_FLAGS_ANYWHERE, handle.m_port, 0, false, vmProtection, vmProtection, VM_INHERIT_NONE); if (kr != KERN_SUCCESS) return 0; RefPtr<SharedMemory> sharedMemory(adoptRef(new SharedMemory)); sharedMemory->m_size = handle.m_size; sharedMemory->m_data = toPointer(mappedAddress); return sharedMemory.release(); }
int main(int argc, char * argv[]) { pthread_t tid[THREADS]; sharedMemory(); int res = sem_init(&count_sem, 0, 1); // 0 is locked if(res < 0) { perror("Semaphore initialization failed"); exit(0); } unsigned int i, id[THREADS]; for(i = 0; i < THREADS; i++) { id[i] = i; if(pthread_create(&tid[i], NULL, Count, (void* ) &id[i])) { printf("\n ERROR creating thread %d", i+1); exit(1); } } for(i = 0; i < THREADS; i++) { if(pthread_join(tid[i], NULL)) // wait for the thread i to finish { printf("\n ERROR joining thread"); exit(1); } } if (*cnt != THREADS*NITER) printf("\n BOOM! cnt is [%d], should be %d\n", *cnt, THREADS*NITER); else printf("\n OK! cnt is [%d]\n", *cnt); sem_destroy(&count_sem); dtachMemory(); pthread_exit(NULL); }
void FileLoader::loadFile(const QString &fileName) { //! [1] // Try to open the file ... QFile file(QString::fromLatin1("app/native/assets/files/%1").arg(fileName)); if (!file.open(QIODevice::ReadOnly)) { m_status = tr("Unable to open file: %1").arg(file.errorString()); emit statusChanged(); return; } // ... and read its complete content into a temporary variable const QByteArray content = file.readAll(); file.close(); //! [1] //! [2] // Try to attach to the shared memory segment with the given key QSharedMemory sharedMemory(QString::fromLatin1(s_sharedKey)); if (!sharedMemory.attach()) { m_status = tr("Unable to attach to shared memory: %1\nPlease start the sharedmemory sample application!").arg(sharedMemory.errorString()); emit statusChanged(); return; } // Lock the shared memory segment before we do any modifications sharedMemory.lock(); // Copy the file content from the temporary variable into the shared memory segment strncpy(static_cast<char*>(sharedMemory.data()), content.constData(), sharedMemory.size() - 1); // Unlock the shared memory segment again ... sharedMemory.unlock(); // ... and detach from it sharedMemory.detach(); //! [2] m_status = tr("Loaded file %1 to shared memory").arg(fileName); emit statusChanged(); }
PassRefPtr<SharedMemory> SharedMemory::create(size_t size) { // On Symbian, global chunks (shared memory segments) have system-unique names, so we pick a random // number from the kernel's random pool and use it as a string. // Using an integer simplifies serialization of the name in Handle::encode() uint32_t random = Math::Random(); TBuf<KMaxKernelName> chunkName; chunkName.Format(_L("%d"), random); RChunk chunk; TInt error = chunk.CreateGlobal(chunkName, size, size); if (error) { qCritical() << "Failed to create WK2 shared memory of size " << size << " with error " << error; return 0; } RefPtr<SharedMemory> sharedMemory(adoptRef(new SharedMemory)); sharedMemory->m_handle = chunk.Handle(); sharedMemory->m_size = chunk.Size(); sharedMemory->m_data = static_cast<void*>(chunk.Base()); return sharedMemory.release(); }
int main(int argc, char *argv[]) { QApplication app(argc, argv); QSplashScreen screen(QPixmap(":/images/chargement.png")); screen.show(); app.processEvents(); //Traduction des boutons QString locale = QLocale::system().name().section('_', 0, 0); QTranslator translator; translator.load(QString("qt_") + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)); app.installTranslator(&translator); //----------------------------------------------------- // Vérification de l'existence d'une autre instance //----------------------------------------------------- app.setApplicationName("Dadaword"); QSharedMemory sharedMemory(app.applicationName()); // On vérifie à la création de cette zone mémoire si celle-ci existe if(sharedMemory.create(sizeof(int))==false){ QMessageBox::warning(0, QObject::tr("Programme en cours d'exécution"), QObject::tr("Dadaword est déjà en cours d'exécution. Veuillez fermer l'instance ouverte avant de le lance à nouveau.")); //exit(EXIT_SUCCESS); } DadaWord instance; //Création de l'interface utilisateur instance.createUI(); //Affichage instance.show(); screen.finish(&instance); return app.exec(); }
PassRefPtr<SharedMemory> SharedMemory::create(const Handle& handle, Protection protection) { if (handle.isNull()) return 0; // Convert number to string, and open the global chunk TBuf<KMaxKernelName> chunkName; chunkName.Format(_L("%d"), handle.m_chunkID); RChunk chunk; // NOTE: Symbian OS doesn't support read-only global chunks. TInt error = chunk.OpenGlobal(chunkName, false); if (error) { qCritical() << "Failed to create WK2 shared memory from handle " << error; return 0; } chunk.Adjust(chunk.MaxSize()); RefPtr<SharedMemory> sharedMemory(adoptRef(new SharedMemory)); sharedMemory->m_handle = chunk.Handle(); sharedMemory->m_size = chunk.Size(); sharedMemory->m_data = static_cast<void*>(chunk.Base()); return sharedMemory.release(); }
void DesktopServerWatcher::execute() { AnonymousPipeFactory pipeFactory(512 * 1024, m_log); AnonymousPipe *ownSidePipeChanTo, *otherSidePipeChanTo, *ownSidePipeChanFrom, *otherSidePipeChanFrom; while (!isTerminating()) { try { StringStorage shMemName(_T("Global\\")); srand((unsigned)time(0)); for (int i = 0; i < 20; i++) { shMemName.appendChar('a' + rand() % ('z' - 'a')); } SharedMemory sharedMemory(shMemName.getString(), 72); UINT64 *mem = (UINT64 *)sharedMemory.getMemPointer(); // Sets memory ready flag to false. mem[0] = 0; ownSidePipeChanTo = otherSidePipeChanTo = ownSidePipeChanFrom = otherSidePipeChanFrom = 0; pipeFactory.generatePipes(&ownSidePipeChanTo, false, &otherSidePipeChanTo, false); pipeFactory.generatePipes(&ownSidePipeChanFrom, false, &otherSidePipeChanFrom, false); // TightVNC server log directory. StringStorage logDir; Configurator::getInstance()->getServerConfig()->getLogFileDir(&logDir); // Arguments that must be passed to desktop server application. StringStorage args; args.format(_T("-desktopserver -logdir \"%s\" -loglevel %d -shmemname %s"), logDir.getString(), Configurator::getInstance()->getServerConfig()->getLogLevel(), shMemName.getString()); m_process->setArguments(args.getString()); start(); // Prepare other side pipe handles for other side m_log->debug(_T("DesktopServerWatcher::execute(): assigning handles")); otherSidePipeChanTo->assignHandlesFor(m_process->getProcessHandle(), false); otherSidePipeChanFrom->assignHandlesFor(m_process->getProcessHandle(), false); // Transfer other side handles by the memory channel mem[1] = (UINT64)otherSidePipeChanTo->getWriteHandle(); mem[2] = (UINT64)otherSidePipeChanTo->getReadHandle(); mem[3] = (UINT64)otherSidePipeChanTo->getMaxPortionSize(); mem[4] = (UINT64)otherSidePipeChanFrom->getWriteHandle(); mem[5] = (UINT64)otherSidePipeChanFrom->getReadHandle(); mem[6] = (UINT64)otherSidePipeChanFrom->getMaxPortionSize(); // Sets memory ready flag to true. mem[0] = 1; // Destroying other side objects delete otherSidePipeChanTo; m_log->debug(_T("DesktopServerWatcher::execute(): Destroyed otherSidePipeChanTo")); otherSidePipeChanTo = 0; delete otherSidePipeChanFrom; m_log->debug(_T("DesktopServerWatcher::execute(): Destroyed otherSidePipeChanFrom")); otherSidePipeChanFrom = 0; m_log->debug(_T("DesktopServerWatcher::execute(): Try to call onReconnect()")); m_recListener->onReconnect(ownSidePipeChanTo, ownSidePipeChanFrom); m_process->waitForExit(); } catch (Exception &e) { // A potentional memory leak. // A potential crash. The channels can be used (see onReconnect()) after these destroyings. if (ownSidePipeChanTo) delete ownSidePipeChanTo; if (otherSidePipeChanTo) delete otherSidePipeChanTo; if (ownSidePipeChanFrom) delete ownSidePipeChanFrom; if (otherSidePipeChanFrom) delete otherSidePipeChanFrom; m_log->error(_T("DesktopServerWatcher has failed with error: %s"), e.getMessage()); Sleep(1000); } } }
int main(int argc, char *argv[]) { Q_INIT_RESOURCE(qgateway); QApplication app(argc, argv); // loading language translation QString locale = QLocale::system().name(); QTranslator translator; translator.load(QCoreApplication::applicationDirPath() + QDir::separator() + "qgateway_" + locale); app.installTranslator(&translator); // checking if application has only one instance QSharedMemory sharedMemory("QGateway"); bool oneInstance = (sharedMemory.create(1) && (sharedMemory.error() != QSharedMemory::AlreadyExists)); if (!oneInstance) { QMessageBox::information(0, "QGateway", QObject::tr("Application is already running!")); return 0; } if (!QSystemTrayIcon::isSystemTrayAvailable()) { QMessageBox::critical(0, "QGateway", QObject::tr("I couldn't detect any system tray " "on this system.")); return 1; } QApplication::setQuitOnLastWindowClosed(false); #ifdef Q_OS_WIN WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD( 2, 2 ); err = WSAStartup( wVersionRequested, &wsaData ); if( err != 0 ) { /* Tell the user that we could not find a usable */ /* WinSock DLL. */ QMessageBox::critical(0, "QGateway", QObject::tr("I couldn't detect required Windows socket library " "on this system.")); return err; } /* Confirm that the WinSock DLL supports 2.2.*/ /* Note that if the DLL supports versions greater */ /* than 2.2 in addition to 2.2, it will still return */ /* 2.2 in wVersion since that is the version we */ /* requested. */ if( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 ) { /* Tell the user that we could not find a usable */ /* WinSock DLL. */ QMessageBox::critical(0, "QGateway", QObject::tr("I couldn't detect required Windows socket library " "on this system.")); WSACleanup(); return 1; } /* The WinSock DLL is acceptable. Proceed. */ #ifdef HAVE_MS_PING // Initialize Icmp handle initMsIcmp(); #endif #endif Window window; int ret = app.exec(); #ifdef Q_OS_WIN #ifdef HAVE_MS_PING // Close Icmp handle shutdownMsIcmp(); #endif WSACleanup(); #endif return ret; }