当前位置: 首页>>代码示例>>C++>>正文


C++ QSharedMemory::lock方法代码示例

本文整理汇总了C++中QSharedMemory::lock方法的典型用法代码示例。如果您正苦于以下问题:C++ QSharedMemory::lock方法的具体用法?C++ QSharedMemory::lock怎么用?C++ QSharedMemory::lock使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QSharedMemory的用法示例。


在下文中一共展示了QSharedMemory::lock方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: slotConnectionEstablished

/**
 * @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;
	}
}
开发者ID:jiangxilong,项目名称:RetroShare,代码行数:36,代码来源:rshare.cpp

示例2: readonly_segfault

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;
}
开发者ID:Drakey83,项目名称:steamlink-sdk,代码行数:10,代码来源:main.cpp

示例3: isRunning

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;
}
开发者ID:chocoop,项目名称:ckb,代码行数:11,代码来源:main.cpp

示例4: timerTick

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();
}
开发者ID:abrefort,项目名称:ckb,代码行数:12,代码来源:mainwindow.cpp

示例5: updateAida

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();
    }
开发者ID:debauer,项目名称:Conflict,代码行数:12,代码来源:conflict_core.cpp

示例6: isRunning

// Check if the application is running. Optionally write something to its shared memory.
static bool isRunning(const char* command){
    // Try to create shared memory (if successful, application was not already running)
    if(!appShare.create(SHMEM_SIZE) || !appShare.lock()){
        // Lock existing shared memory
        if(!appShare.attach() || !appShare.lock())
            return true;
        bool running = false;
        if(appShare.size() == SHMEM_SIZE_V015){
            // Old shmem - no PID listed so assume the process is running, and print the command directly to the buffer
            if(command){
                void* data = appShare.data();
                snprintf((char*)data, SHMEM_SIZE_V015, "%s", command);
            }
            running = true;
        } else {
            // New shmem. Scan the contents of the shared memory for a PID
            QStringList lines = QString((const char*)appShare.constData()).split("\n");
            if(pidActive(lines)){
                running = true;
                // Append the command
                if(command){
                    lines.append(QString("Option ") + command);
                    QByteArray newMem = lines.join("\n").left(SHMEM_SIZE).toLatin1();
                    // Copy the NUL byte as well as the string
                    memcpy(appShare.data(), newMem.constData(), newMem.length() + 1);
                }
            }
        }
        if(running){
            appShare.unlock();
            return true;
        }
    }
    // Not already running. Initialize the shared memory with our PID
    snprintf((char*)appShare.data(), appShare.size(), "PID %ld", (long)getpid());
    appShare.unlock();
    return false;
}
开发者ID:shazron,项目名称:ckb,代码行数:39,代码来源:main.cpp

示例7: consumer

int consumer()
{
    QSharedMemory consumer;
    consumer.setKey("market");

    //qDebug("consumer starting");
    int tries = 0;
    while (!consumer.attach()) {
        if (tries == 5000) {
            qWarning() << "consumer exiting, waiting too long";
            return EXIT_FAILURE;
        }
        ++tries;
        QTest::qSleep(1);
    }
    //qDebug("consumer attached");


    int i = 0;
    while (true) {
        if (!consumer.lock()) {
            qWarning() << "Could not lock" << consumer.key();
            return EXIT_FAILURE;
        }
        if (get(consumer, 0) == 'Q') {
            set(consumer, 0, ++i);
            //qDebug() << "consumer sets" << i;
        }
        if (get(consumer, 0) == 'E') {
            if (!consumer.unlock()) {
                qWarning() << "Could not unlock" << consumer.key();
                return EXIT_FAILURE;
            }
            break;
        }
        if (!consumer.unlock()) {
            qWarning() << "Could not unlock" << consumer.key();
            return EXIT_FAILURE;
        }
        QTest::qSleep(10);
    }

    //qDebug("consumer detaching");
    if (!consumer.detach()) {
        qWarning() << "Could not detach" << consumer.key();
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
开发者ID:Drakey83,项目名称:steamlink-sdk,代码行数:49,代码来源:main.cpp

示例8: isRunning

bool Application::isRunning()
{
    bool running = BaseApplication::isRunning();
    QSharedMemory *sharedMem = new QSharedMemory(id() + QLatin1String("-shared-memory-key"), this);
    if (!running) {
        // First instance creates shared memory and store PID
        if (sharedMem->create(sizeof(DWORD)) && sharedMem->lock()) {
            *(static_cast<DWORD*>(sharedMem->data())) = ::GetCurrentProcessId();
            sharedMem->unlock();
        }
    }
    else {
        // Later instances attach to shared memory and retrieve PID
        if (sharedMem->attach() && sharedMem->lock()) {
            ::AllowSetForegroundWindow(*(static_cast<DWORD*>(sharedMem->data())));
            sharedMem->unlock();
        }
    }

    if (!sharedMem->isAttached())
        qWarning() << "Failed to initialize shared memory: " << sharedMem->errorString();

    return running;
}
开发者ID:suratovvlad,项目名称:qBittorrent,代码行数:24,代码来源:application.cpp

示例9: storeSharedData

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;
}
开发者ID:jppiiroinen,项目名称:cutedriver-agent_qt,代码行数:19,代码来源:tasdatashare.cpp

示例10: in

// 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());
}
开发者ID:bvgastel,项目名称:xmas,代码行数:22,代码来源:main.cpp

示例11: lock_jt9_

bool lock_jt9_() {return mem_jt9.lock();}
开发者ID:BackupTheBerlios,项目名称:wsjt-svn,代码行数:1,代码来源:ipcomm.cpp

示例12: producer

int producer()
{
    QSharedMemory producer;
    producer.setKey("market");

    int size = 1024;
    if (!producer.create(size)) {
        if (producer.error() == QSharedMemory::AlreadyExists) {
            if (!producer.attach()) {
                qWarning() << "Could not attach to" << producer.key();
                return EXIT_FAILURE;
            }
        } else {
            qWarning() << "Could not create" << producer.key();
            return EXIT_FAILURE;
        }
    }
    // tell parent we're ready
    //qDebug("producer created and attached");
    puts("");
    fflush(stdout);

    if (!producer.lock()) {
        qWarning() << "Could not lock" << producer.key();
        return EXIT_FAILURE;
    }
    set(producer, 0, 'Q');
    if (!producer.unlock()) {
        qWarning() << "Could not lock" << producer.key();
        return EXIT_FAILURE;
    }

    int i = 0;
    while (i < 5) {
        if (!producer.lock()) {
            qWarning() << "Could not lock" << producer.key();
            return EXIT_FAILURE;
        }
        if (get(producer, 0) == 'Q') {
            if (!producer.unlock()) {
                qWarning() << "Could not unlock" << producer.key();
                return EXIT_FAILURE;
            }
            QTest::qSleep(1);
            continue;
        }
        //qDebug() << "producer:" << i);
        ++i;
        set(producer, 0, 'Q');
        if (!producer.unlock()) {
            qWarning() << "Could not unlock" << producer.key();
            return EXIT_FAILURE;
        }
        QTest::qSleep(1);
    }
    if (!producer.lock()) {
        qWarning() << "Could not lock" << producer.key();
        return EXIT_FAILURE;
    }
    set(producer, 0, 'E');
    if (!producer.unlock()) {
        qWarning() << "Could not unlock" << producer.key();
        return EXIT_FAILURE;
    }

    //qDebug("producer done");

    // Sleep for a bit to let all consumers exit
    getchar();
    return EXIT_SUCCESS;
}
开发者ID:Drakey83,项目名称:steamlink-sdk,代码行数:71,代码来源:main.cpp

示例13: out

/** Constructor. Parses the command-line arguments, resets Rshare's
 * configuration (if requested), and sets up the GUI style and language
 * translation. */
Rshare::Rshare(QStringList args, int &argc, char **argv, const QString &dir)
: QApplication(argc, argv)
{
  mStartupTime = QDateTime::currentDateTime();
  localServer = NULL;

  //Initialize connection to LocalServer to know if other process runs.
  {
    QString serverName = QString(TARGET);

    if (!args.isEmpty()) {
      // load into shared memory
      QBuffer buffer;
      buffer.open(QBuffer::ReadWrite);
      QDataStream out(&buffer);
      out << args;
      int size = buffer.size();

      QSharedMemory newArgs;
      newArgs.setKey(serverName + "_newArgs");
      if (newArgs.isAttached()) newArgs.detach();

      if (!newArgs.create(size)) {
        std::cerr << "(EE) Rshare::Rshare Unable to create shared memory segment of size:"
                  << size << " error:" << newArgs.errorString().toStdString() << "." << std::endl;
#ifdef Q_OS_UNIX
        std::cerr << "Look with `ipcs -m` for nattch==0 segment. And remove it with `ipcrm -m 'shmid'`." << std::endl;
        //No need for windows, as it removes shared segment directly even when crash.
#endif
        newArgs.detach();
        ::exit(EXIT_FAILURE);
      }
      newArgs.lock();
      char *to = (char*)newArgs.data();
      const char *from = buffer.data().data();
      memcpy(to, from, qMin(newArgs.size(), size));
      newArgs.unlock();

      // Connect to the Local Server of the main process to notify it
      // that a new process had been started
      QLocalSocket localSocket;
      localSocket.connectToServer(QString(TARGET));

      std::cerr << "Rshare::Rshare waitForConnected to other instance." << std::endl;
      if( localSocket.waitForConnected(100) )
      {
        std::cerr << "Rshare::Rshare Connection etablished. Waiting for disconnection." << std::endl;
        localSocket.waitForDisconnected(1000);
        newArgs.detach();
        std::cerr << "Rshare::Rshare Arguments was sended." << std::endl
                  << " To disable it, in Options - General - Misc," << std::endl
                  << " uncheck \"Use Local Server to get new Arguments\"." << std::endl;
        ::exit(EXIT_SUCCESS); // Terminate the program using STDLib's exit function
      }
      newArgs.detach();
    }
    // No main process exists
    // Or started without arguments
    // So we start a Local Server to listen for connections from new process
    localServer= new QLocalServer();
    QObject::connect(localServer, SIGNAL(newConnection()), this, SLOT(slotConnectionEstablished()));
    updateLocalServer();
  }

#if QT_VERSION >= QT_VERSION_CHECK (5, 0, 0)
  qInstallMessageHandler(qt_msg_handler);
#else
  qInstallMsgHandler(qt_msg_handler);
#endif

#ifndef __APPLE__

  /* set default window icon */
  setWindowIcon(QIcon(":/icons/logo_128.png"));

#endif

  mBlink = true;
  QTimer *timer = new QTimer(this);
  timer->setInterval(500);
  connect(timer, SIGNAL(timeout()), this, SLOT(blinkTimer()));
  timer->start();

  timer = new QTimer(this);
  timer->setInterval(60000);
  connect(timer, SIGNAL(timeout()), this, SIGNAL(minuteTick()));
  timer->start();

  /* Read in all our command-line arguments. */
  parseArguments(args);

  /* Check if we're supposed to reset our config before proceeding. */
  if (_args.contains(ARG_RESET)) {
    Settings->reset();
  }
  
  /* Handle the -loglevel and -logfile options. */
//.........这里部分代码省略.........
开发者ID:jiangxilong,项目名称:RetroShare,代码行数:101,代码来源:rshare.cpp

示例14: a

int
main(int argc, char *argv[])
{
    QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QApplication a(argc, argv);

    auto startMinimized = false;
    QString uri = "";

    for (auto string : QCoreApplication::arguments()) {
        if (string == "-m" || string == "--minimized")
            startMinimized = true;
        if (string == "-d" || string == "--debug")
            Console();
        if (string.startsWith("ring:")) {
            uri = string;
        }
    }

#ifdef URI_PROTOCOL
    QSharedMemory* shm = new QSharedMemory("RingShm");
    QSystemSemaphore* sem = new QSystemSemaphore("RingSem", 0);

    if (not shm->create(1024)) {
        if (not uri.isEmpty()) {
            shm->attach();
            shm->lock();
            char *to = (char*) shm->data();
            QChar *data = uri.data();
            while (!data->isNull())
            {
                memset(to, data->toLatin1(), 1);
                ++data;
                ++to;
            }
            memset(to, 0, 1); //null terminator
            shm->unlock();
        }
        sem->release();

        delete shm;
        exit(EXIT_SUCCESS);
    }
    //Client listening to shm event
    memset((char*)shm->data(), 0, shm->size());
    ShmClient* shmClient = new ShmClient(shm, sem);
#endif

    QTranslator qtTranslator;
    qtTranslator.load("qt_" + QLocale::system().name(),
                      QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    a.installTranslator(&qtTranslator);

    QTranslator lrcTranslator;
    lrcTranslator.load("share/libringclient/translations/lrc_" + QLocale::system().name());
    a.installTranslator(&lrcTranslator);

    QTranslator mainTranslator;
    mainTranslator.load("share/ring/translations/ring_client_windows_" + QLocale::system().name());
    a.installTranslator(&mainTranslator);

    QFont font;
    font.setFamily("Segoe UI");
    a.setFont(font);

    QFile file(":/stylesheet.css");
    if(file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        a.setStyleSheet(file.readAll());
        file.close();
    }

    QCoreApplication::setOrganizationName("Savoir-faire Linux");
    QCoreApplication::setOrganizationDomain("ring.cx");
    QCoreApplication::setApplicationName("Ring");

    if (not uri.isEmpty()) {
        startMinimized = false;
        MainWindow::instance().onRingEvent(uri);
    }

    if (not startMinimized)
        MainWindow::instance().show();
    else {
        MainWindow::instance().showMinimized();
        MainWindow::instance().hide();
    }

    MainWindow::instance().createThumbBar();

#ifdef URI_PROTOCOL
    QObject::connect(shmClient, SIGNAL(RingEvent(QString)), &MainWindow::instance(), SLOT(onRingEvent(QString)));

    QObject::connect(&a, &QApplication::aboutToQuit, [&a, &shmClient, &shm, &sem]() {
        shmClient->terminate();
        delete shmClient;
        delete shm;
        delete sem;
    });
//.........这里部分代码省略.........
开发者ID:savoirfairelinux,项目名称:ring-client-windows,代码行数:101,代码来源:main.cpp


注:本文中的QSharedMemory::lock方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。