예제 #1
0
int main(int argc, const char * argv[]) {

    int key; //unique integer identifier for the shared memory region to be created, attached to, or
             //detached from
    void *address; //pointer to the lowest (virtual) address in the shared memory region
    sem_t semID; //semaphore ID
	int err; //error code from a system call
	int i; //used for a counter
	
	key = 12345;
    
    //create a two-page shared region (each page is 4K bytes)
    err = shmem(key,2, (void **) &address);
	
	if (err != 0) {
	    printf("shmem failed in shmdemo 1; error code = %d\n", err);
	    exit(1);
	}
    
    //fill all except first 4 bytes with random ints (each int is 4 bytes long)
    //--original number is 2048 because each page is 1024 and there are 2 pages--
    for(i=1;i<=2047;i++)
    {
	    address[i] = rand();
    }
    
    //create semophore with initial count of 0
	semID =  newsema(0);
   
   	if (semID < 0) 
   	{
	    printf("newsema failed; error code = %d\n", (int)semID);
	    shmem(key,0,(void **)&address);	/* free the shared memory */
	    exit(1);
	}
    
    //put semID in the first 4 bytes of shared memory region
    address[0] = int(semID);
    
    printf("\nWaiting on the second process....\n");
    
    //do a down operation on a semaphore (5 min)
    //if time runs out, throw an error
    if(down(semID,300000) == TIMEOUT)
	{
		printf("shmdemo 1 timed out.\n");
	}
    else
	{
	    printf("Successfully returned to shmdemo 1.\n");
	}
	
	shmem(key,0,(void **)&address);
	freesema(semID);
    return 0;
}
예제 #2
0
Shmem::SharedMemory*
IToplevelProtocol::CreateSharedMemory(size_t aSize,
                                      Shmem::SharedMemory::SharedMemoryType aType,
                                      bool aUnsafe,
                                      Shmem::id_t* aId)
{
  RefPtr<Shmem::SharedMemory> segment(
    Shmem::Alloc(Shmem::IHadBetterBeIPDLCodeCallingThis_OtherwiseIAmADoodyhead(), aSize, aType, aUnsafe));
  if (!segment) {
    return nullptr;
  }
  int32_t id = GetSide() == ParentSide ? ++mLastShmemId : --mLastShmemId;
  Shmem shmem(
    Shmem::IHadBetterBeIPDLCodeCallingThis_OtherwiseIAmADoodyhead(),
    segment.get(),
    id);
  Message* descriptor = shmem.ShareTo(
    Shmem::IHadBetterBeIPDLCodeCallingThis_OtherwiseIAmADoodyhead(), OtherPid(), MSG_ROUTING_CONTROL);
  if (!descriptor) {
    return nullptr;
  }
  Unused << GetIPCChannel()->Send(descriptor);

  *aId = shmem.Id(Shmem::IHadBetterBeIPDLCodeCallingThis_OtherwiseIAmADoodyhead());
  Shmem::SharedMemory* rawSegment = segment.get();
  mShmemMap.AddWithID(segment.forget().take(), *aId);
  return rawSegment;
}
예제 #3
0
TLevelP TLevelReaderMov::loadInfo() {
  QLocalSocket socket;
  tipc::startSlaveConnection(&socket, t32bitsrv::srvName(), -1,
                             t32bitsrv::srvCmdline());

  tipc::Stream stream(&socket);
  tipc::Message msg;

  TLevelP level;
  {
    QString shMemId(tipc::uniqueId());

    // Send the appropriate command
    stream << (msg << QString("$LRMovLoadInfo") << m_id << shMemId);
    if (tipc::readMessage(stream, msg) != "ok") goto err;

    int frameCount;

    msg >> frameCount >> tipc::clr;

    // Read the data in the shared memory segment
    QSharedMemory shmem(shMemId);
    shmem.attach();
    shmem.lock();

    int *f, *fBegin = (int *)shmem.data(), *fEnd = fBegin + frameCount;
    assert(fBegin);

    for (f = fBegin; f < fEnd; ++f) level->setFrame(*f, TImageP());

    shmem.unlock();
    shmem.detach();

    // Release the shared memory segment
    stream << (msg << QString("$shmem_release") << shMemId);
    if (tipc::readMessage(stream, msg) != "ok") goto err;
  }

  return level;

err:

  throw TException("Couldn't read movie data");
  return TLevelP();
}
예제 #4
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    {
        QSharedMemory shmem("GOSTunnel-gui");
        shmem.attach();
    }

    shmem = new QSharedMemory("GOSTunnel-gui");
    if (shmem->attach()) {
        QMessageBox::warning(this,
                             tr("Ошибка открытия приложения"),
                             tr("Приложение уже запущенно!"));
        exit(1);
    } else {
        shmem->create(1);
    }

    ui->setupUi(this);

    isShowMsgTray = false;
    mainSettings = NULL;
    setWindowTitle("GOSTunnel-gui");
    setWindowFlags(Qt::WindowMinimizeButtonHint |
                   Qt::WindowCloseButtonHint |
                   Qt::MSWindowsFixedSizeDialogHint);
    loadSettings(QCoreApplication::applicationDirPath() + "/config.txt");
    loadConfigs(programConfig);
    this->setTrayIconActions();
    this->showTrayIcon();

    ui->lwGroups->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->lwGroups, SIGNAL(customContextMenuRequested(QPoint)),
            this, SLOT(showContextMenuForGroupsList(QPoint)));
    QAction *renameAction = new QAction(tr("Переименовать"), this);
    QAction *deleteAction = new QAction(tr("Удалить"), this);
    connect(deleteAction, SIGNAL(triggered()),
            this, SLOT(on_btnDeletegroup_clicked()));
    connect(renameAction, SIGNAL(triggered()),
            this, SLOT(triggeredRenameAction()));
    lwMenu = new QMenu(tr("Context menu"), this);
    lwMenu->addAction(renameAction);
    lwMenu->addAction(deleteAction);
}
예제 #5
0
int main (int argc, const char * argv[])
{
    int i,sum;
    sem_t semID; //semaphore ID
    void *address;
    int key; //unique integer identifier for the shared memory region to be created, attached to, or
    //detached from
    
    //map the shared memory region into an address space using
    //shmem system call
    shmem();
    
    
    //compute the sum of the 2047 4-byte integers in the two-page
    //shared memory region
    for (i=0; i<2047; i++)
    {
        <#statements#>
    }
    
    //place the sum in the second integer
    //in the shared memory region
    
    
    //display the sum on the console
    printf("The sum of the 2047 integers is: %d\n", sum);
    
    //do an up on the semaphore whose ID is the first 4-bytes of the
    //shared memory region
    semID = address[0];
    up(semID);
    
    //free the shared memory region
    
    return 0;
}
예제 #6
0
  /** Tests the dynamic shmem utility
   * @param arg_id : The id of the test */
  void test_shmem(const int arg_id)
  {
    bool flag = true;
    unsigned int test_id=0;
    pid_t pid_child = 1;
    try
    {
      //Create shared memory object, id 8080
      sutil::CSharedMemory<SShmObj, char> shmem(8080,'x');

      std::cout<<std::flush;

      pid_child = fork();

      if(0 == pid_child)
      {//Child process (client)
        sleep(1);//Sleep for 1 sec while the parent creates the shared memory

        std::cout<<"\nTest Result ("<<test_id++<<") Client: I am alive! My pid is: "<<pid_child;

        //3. Read the shared memory
        flag = shmem.shmRead();
        if(false == flag)
        { throw(std::runtime_error("Client: Failed to read shared memory"));  }
        else
        { std::cout<<"\nTest Result ("<<test_id++<<") Client: Read the shared memory"; }

        //4. Modify the shared memory
        std::cout<<"\nTest Result ("<<test_id++<<") Client: Setting the shared memory";
        strcpy(shmem.data_->x, "Namaste Parent-Server! I am your child-client.");
        std::cout<<"\nTest Result ("<<test_id++<<") Client: Data: "<< std::string(shmem.data_->x);

        //5. Signal the server and go to sleep
        std::cout<<"\nTest Result ("<<test_id++<<") Client: Signaling server";
        std::cout<<std::flush;
        *shmem.data_signal_ = 'a';

        while(*shmem.data_signal_ != 'b')
        { sleep(1); }

        //8. Read the server's message and terminate
        std::cout<<"\nTest Result ("<<test_id++<<") Client: Message from server: "<< std::string(shmem.data_->x);

        flag = shmem.shmDetach();
        if(false == flag)
        { throw(std::runtime_error("Client: Failed to read shared memory"));  }
        else
        { std::cout<<"\nTest Result ("<<test_id++<<") Client: Terminated. Adieu!"; }
      }
      else
      {//Parent process (server)
        std::cout<<"\nTest Result ("<<test_id++<<") Server: I spawned a child! Its pid is: "<<pid_child;

        //1. Create the shared memory
        flag = shmem.shmCreate();
        if(false == flag)
        { throw(std::runtime_error("Server: Failed to create shared memory"));  }
        else
        { std::cout<<"\nTest Result ("<<test_id++<<") Server: Created shared memory"; }

        //2. Wait for client to manipulate the shared memory and go to sleep
        std::cout<<"\nTest Result ("<<test_id++<<") Server: Waiting for client signal";

        std::cout<<std::flush;
        *shmem.data_signal_ = '0';
        while(*shmem.data_signal_ != 'a')
        { sleep(1); }

        //6. Read the client's message and manipulate the shared memory
        std::cout<<"\nTest Result ("<<test_id++<<") Server: Message from client: "<< std::string(shmem.data_->x);

        std::cout<<"\nTest Result ("<<test_id++<<") Server: Setting the shared memory";
        strcpy(shmem.data_->x, "Greetings child.");
        std::cout<<"\nTest Result ("<<test_id++<<") Server: Data: "<< std::string(shmem.data_->x);

        //7. Signal the client and get ready to terminate
        std::cout<<std::flush;
        *shmem.data_signal_ = 'b';

        //Checks whether the shmem signal is 'x', and terminates when it is
        while(!shmem.shmCheckDetach())
        { sleep(1); }
        std::cout<<"\nTest Result ("<<test_id++<<") Server: Client terminated, detaching shared memory";

        //9. Client terminated.
        std::cout<<"\nTest #"<<arg_id<<" (Shared Memory Test) Succeeded.";
      }
    }
    catch(std::exception& ee)
    {
      std::cout<<"\nTest Error ("<<test_id++<<") "<<ee.what();
      std::cout<<"\nTest #"<<arg_id<<" (Shared Memory Test) Failed";
    }

    if(0 == pid_child)//The child process doesn't need to continue.
    { exit(0);  }
  }
예제 #7
0
int main(int argc, char * argv[])
{
    /*
     * Before starting main application, need to set 'QT_X11_NO_MITSHM=1'
     * to make the runtime work with IBM PPC machine.
     */
#if defined (Q_OS_LINUX)
    QByteArray val("1");
    qputenv("QT_X11_NO_MITSHM", val);
#endif

    // Create the QT application
    QApplication app(argc, argv);
    app.setQuitOnLastWindowClosed(false);

    // Setup the settings management
    QCoreApplication::setOrganizationName("pgadmin");
    QCoreApplication::setOrganizationDomain("pgadmin.org");
    QCoreApplication::setApplicationName(PGA_APP_NAME.toLower().replace(" ", ""));

#if QT_VERSION >= 0x050000
    // Set high DPI pixmap to display icons clear on Qt widget.
    QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif

    // Create a hash of the executable path so we can run copies side-by-side
    QString homeDir = QDir::homePath();
    unsigned long exeHash = sdbm((unsigned char *)argv[0]);

    // Create the address file, that will be used to store the appserver URL for this instance
    addrFileName = homeDir + (QString("/.%1.%2.addr").arg(PGA_APP_NAME).arg(exeHash)).remove(" ");
    QFile addrFile(addrFileName);

    // Create a system-wide semaphore keyed by app name, exe hash and the username
    // to ensure instances are unique to the user and path
    QString userName = qgetenv("USER"); // *nix
    if (userName.isEmpty())
        userName = qgetenv("USERNAME"); // Windows

    QString semaName = QString("%1-%2-%3-sema").arg(PGA_APP_NAME).arg(userName).arg(exeHash);
    QString shmemName = QString("%1-%2-%3-shmem").arg(PGA_APP_NAME).arg(userName).arg(exeHash);

    QSystemSemaphore sema(semaName, 1);
    sema.acquire();

#ifndef Q_OS_WIN32
    // We may need to clean up stale shmem segments on *nix. Attaching and detaching
    // should remove the segment if it is orphaned.
    QSharedMemory stale_shmem(shmemName);
    if (stale_shmem.attach())
        stale_shmem.detach();
#endif

    QSharedMemory shmem(shmemName);
    bool is_running;
    if (shmem.attach())
    {
        is_running = true;
    }
    else
    {
        shmem.create(1);
        is_running = false;
    }
    sema.release();

    QSettings settings;

    if (is_running){
        addrFile.open(QIODevice::ReadOnly | QIODevice::Text);
        QTextStream in(&addrFile);
        QString addr = in.readLine();

        QString cmd = settings.value("BrowserCommand").toString();

        if (!cmd.isEmpty())
        {
            cmd.replace("%URL%", addr);
            QProcess::startDetached(cmd);
        }
        else
        {
            if (!QDesktopServices::openUrl(addr))
            {
                QString error(QWidget::tr("Failed to open the system default web browser. Is one installed?."));
                QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error);

                exit(1);
            }
        }

        return 0;
    }

    atexit(cleanup);

    // In windows and linux, it is required to set application level proxy
    // because socket bind logic to find free port gives socket creation error
    // when system proxy is configured. We are also setting
    // "setUseSystemConfiguration"=true to use the system proxy which will
    // override this application level proxy. As this bug is fixed in Qt 5.9 so
    // need to set application proxy for Qt version < 5.9.
    //
#if defined (Q_OS_WIN) && QT_VERSION <= 0x050800
    // Give dummy URL required to find proxy server configured in windows.
    QNetworkProxyQuery proxyQuery(QUrl("https://www.pgadmin.org"));
    QNetworkProxy l_proxy;
    QList<QNetworkProxy> listOfProxies = QNetworkProxyFactory::systemProxyForQuery(proxyQuery);

    if (listOfProxies.size())
    {
        l_proxy = listOfProxies[0];

        // If host name is not empty means proxy server is configured.
        if (!l_proxy.hostName().isEmpty()) {
            QNetworkProxy::setApplicationProxy(QNetworkProxy());
        }
    }
#endif

#if defined (Q_OS_LINUX) && QT_VERSION <= 0x050800
    QByteArray proxy_env;
    proxy_env = qgetenv("http_proxy");
    // If http_proxy environment is defined in linux then proxy server is configured.
    if (!proxy_env.isEmpty()) {
        QNetworkProxy::setApplicationProxy(QNetworkProxy());
    }
#endif

    // Display the spash screen
    QSplashScreen *splash = new QSplashScreen();
    splash->setPixmap(QPixmap(":/splash.png"));
    splash->show();
    app.processEvents(QEventLoop::AllEvents);

    quint16 port = 0L;

    // Find an unused port number. Essentially, we're just reserving one
    // here that Flask will use when we start up the server.
    // In order to use the socket, we need to free this socket ASAP.
    // Hence - putting this code in a code block so the scope of the socket
    // variable vanishes to make that socket available.
    {
#if QT_VERSION >= 0x050000
        QTcpSocket socket;

        #if QT_VERSION >= 0x050900
        socket.setProxy(QNetworkProxy::NoProxy);
        #endif

        socket.bind(0, QTcpSocket::ShareAddress);
#else
        QUdpSocket socket;
        socket.bind(0, QUdpSocket::ShareAddress);
#endif
        port = socket.localPort();
    }

    // Generate a random key to authenticate the client to the server
    QString key = QUuid::createUuid().toString();
    key = key.mid(1, key.length() - 2);

    // Generate the filename for the log
    logFileName = homeDir + (QString("/.%1.%2.log").arg(PGA_APP_NAME).arg(exeHash)).remove(" ");

    // Start the tray service
    TrayIcon *trayicon = new TrayIcon(logFileName);

    if (!trayicon->Init())
    {
        QString error = QString(QWidget::tr("An error occurred initialising the tray icon"));
        QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error);

        exit(1);
    }

    // Fire up the webserver
    Server *server;

    bool done = false;

    while (done != true)
    {
        server = new Server(port, key, logFileName);

        if (!server->Init())
        {
            splash->finish(NULL);

            qDebug() << server->getError();

            QString error = QString(QWidget::tr("An error occurred initialising the application server:\n\n%1")).arg(server->getError());
            QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error);

            exit(1);
        }

        server->start();

        // This is a hack to give the server a chance to start and potentially fail. As
        // the Python interpreter is a synchronous call, we can't check for proper startup
        // easily in a more robust way - we have to rely on a clean startup not returning.
        // It should always fail pretty quickly, and take longer to start if it succeeds, so
        // we don't really get a visible delay here.
        delay(1000);

        // Any errors?
        if (server->isFinished() || server->getError().length() > 0)
        {
            splash->finish(NULL);

            qDebug() << server->getError();

            QString error = QString(QWidget::tr("An error occurred initialising the application server:\n\n%1")).arg(server->getError());
            QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error);

            // Allow the user to tweak the Python Path if needed
            bool ok;

            ConfigWindow *dlg = new ConfigWindow();
            dlg->setWindowTitle(QWidget::tr("Configuration"));
            dlg->setBrowserCommand(settings.value("BrowserCommand").toString());
            dlg->setPythonPath(settings.value("PythonPath").toString());
            dlg->setApplicationPath(settings.value("ApplicationPath").toString());
            dlg->setModal(true);
            ok = dlg->exec();

            QString browsercommand = dlg->getBrowserCommand();
            QString pythonpath = dlg->getPythonPath();
            QString applicationpath = dlg->getApplicationPath();

            if (ok)
            {
                settings.setValue("BrowserCommand", browsercommand);
                settings.setValue("PythonPath", pythonpath);
                settings.setValue("ApplicationPath", applicationpath);
                settings.sync();
            }
            else
            {
                exit(1);
            }

            delete server;
        }
        else
            done = true;
    }

    // Ensure the server gets cleaned up later
    QObject::connect(server, SIGNAL(finished()), server, SLOT(deleteLater()));

    // Generate the app server URL
    QString appServerUrl = QString("http://127.0.0.1:%1/?key=%2").arg(port).arg(key);

    // Read the server connection timeout from the registry or set the default timeout.
    int timeout = settings.value("ConnectionTimeout", 30).toInt();

    // Now the server should be up, we'll attempt to connect and get a response.
    // We'll retry in a loop a few time before aborting if necessary.

    QTime endTime = QTime::currentTime().addSecs(timeout);
    bool alive = false;

    while(QTime::currentTime() <= endTime)
    {
        alive = PingServer(QUrl(appServerUrl));

        if (alive)
        {
            break;
        }

        delay(200);
    }

    // Attempt to connect one more time in case of a long network timeout while looping
    if (!alive && !PingServer(QUrl(appServerUrl)))
    {
        splash->finish(NULL);
        QString error(QWidget::tr("The application server could not be contacted."));
        QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error);

        exit(1);
    }

    // Stash the URL for any duplicate processes to open
    if (addrFile.open(QIODevice::WriteOnly))
    {
        addrFile.setPermissions(QFile::ReadOwner|QFile::WriteOwner);
        QTextStream out(&addrFile);
        out << appServerUrl << endl;
    }

    // Go!
    trayicon->setAppServerUrl(appServerUrl);
    // Enable the shutdown server menu as server started successfully.
    trayicon->enableShutdownMenu();

    QString cmd = settings.value("BrowserCommand").toString();

    if (!cmd.isEmpty())
    {
        cmd.replace("%URL%", appServerUrl);
        QProcess::startDetached(cmd);
    }
    else
    {
        if (!QDesktopServices::openUrl(appServerUrl))
        {
            QString error(QWidget::tr("Failed to open the system default web browser. Is one installed?."));
            QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error);

            exit(1);
        }
    }

    QObject::connect(trayicon, SIGNAL(shutdownSignal(QUrl)), server, SLOT(shutdown(QUrl)));

    splash->finish(NULL);

    return app.exec();
}
예제 #8
0
int main(int argc, char *argv[])
{
    int which;			/* which way was the program invoked? */
    int err;			/* error code from a system call */
    int *mem;			/* pointer to the shared memory region */
    int i;			/* loop index */
    sem_t s;			/* semaphore ID */

    if (argc == 2)
        which = atoi(argv[1]);
    if (argc != 2 || which < 1 || which > 2) {
        printf("Usage:    shmdemo 1    -or-    shmdemo 2\n");
        printf("Look at the program source code for details on operation.\n");
        return 1;
    }

    if (which == 1) {
        err = shmem(12345,1,(void **)&mem);
        if (err != 0) {
            printf("shmem failed in shmdemo 1; error code = %d\n", err);
            exit(1);
        }
        s = newsema(0);
        if (s < 0) {
            printf("newsema failed; error code = %d\n", (int)s);
            shmem(12345,0,(void **)&mem);	/* free the shared memory */
            exit(1);
        }
        mem[0] = (int)s;
        for(i=1; i<=100; i++)
            mem[i] = i;
        if (down(s,60 * 1000) == TIMEOUT)	/* one minute, for now XXX */
            printf("shmdemo 1 timed out.\n");
        else
            printf("Successfully returned to shmdemo 1.\n");
        shmem(12345,0,(void **)&mem);
        freesema(s);
        return 0;
    }

    if (which == 2) {
        err = shmem(12345,1,(void **)&mem);
        if (err != 0) {
            printf("shmem failed in shmdemo 2; error code = %d\n", err);
            exit(1);
        }
        err = 0;	/* this is 0 anyway, but we'll be explicit */
        for(i=1; i<=100; i++) {
            if (mem[i] != i) {
                err = i;
                break;
            }
        }
        if (err) {
            printf("shmdemo 2 error: value in mem[%d] = %d.\n", err, mem[err]);
            printf("                 It should be %d\n", err);
        } else
            printf("shmdemo 2: all integer values are as expected.\n");
        s = (sem_t)mem[0];
        shmem(12345,0,(void **)&mem);
        up(s);
        return 0;
    }
}