示例#1
0
void LogViewer::cancelClicked(void)
{
    QString tempDir = gCoreContext->GetSetting("MythArchiveTempDir", "");
    QFile lockFile(tempDir + "/logs/mythburncancel.lck");

    if (!lockFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
        LOG(VB_GENERAL, LOG_ERR,
            "LogViewer: Failed to create mythburncancel.lck file");

    lockFile.write("Cancel\n\r");
    lockFile.close();

    ShowOkPopup(tr("Background creation has been asked to stop.\n" 
                   "This may take a few minutes."));
}
示例#2
0
文件: main.cpp 项目: dejora/ricochet
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    a.setApplicationVersion(QLatin1String("1.1.1"));
    a.setOrganizationName(QStringLiteral("Ricochet"));

#if !defined(Q_OS_WIN) && !defined(Q_OS_MAC)
    a.setWindowIcon(QIcon(QStringLiteral(":/icons/ricochet.svg")));
#endif

    QScopedPointer<SettingsFile> settings(new SettingsFile);
    SettingsObject::setDefaultFile(settings.data());

    QString error;
    QLockFile *lock = 0;
    if (!initSettings(settings.data(), &lock, error)) {
        QMessageBox::critical(0, qApp->translate("Main", "Ricochet Error"), error);
        return 1;
    }
    QScopedPointer<QLockFile> lockFile(lock);

    initTranslation();

    /* Initialize OpenSSL's allocator */
    CRYPTO_malloc_init();

    /* Seed the OpenSSL RNG */
    if (!SecureRNG::seed())
        qFatal("Failed to initialize RNG");
    qsrand(SecureRNG::randomInt(UINT_MAX));

    /* Tor control manager */
    Tor::TorManager *torManager = Tor::TorManager::instance();
    torManager->setDataDirectory(QFileInfo(settings->filePath()).path() + QStringLiteral("/tor/"));
    torControl = torManager->control();
    torManager->start();

    /* Identities */
    identityManager = new IdentityManager;
    QScopedPointer<IdentityManager> scopedIdentityManager(identityManager);

    /* Window */
    QScopedPointer<MainWindow> w(new MainWindow);
    if (!w->showUI())
        return 1;

    return a.exec();
}
示例#3
0
bool ApplicationManager::acquireApplicationLock()
{
    QFile lockFile(CevirgecConstants::LOCK_FILE_PATH());
    if(lockFile.exists()){
        return false;
    }

    if(!lockFile.open(QIODevice::WriteOnly | QIODevice::Text)){
        qWarning("@ApplicationManager::acquireApplicationLock: Cannot create lock file");
        return false;
    }

    qDebug() << "@ApplicationManager::acquireApplicationLock: Lock file created at " << CevirgecConstants::LOCK_FILE_PATH();
    lockFile.close();
    return true;
}
示例#4
0
int NConfig::convert(const char *filename)
{
	if (fd < 0)
		return NC_ERR_NFILE;

	FILE *f = fopen(filename, "w");
	if (!f)
		return NC_ERR_PERM;

	lockFile(NC_L_RO);
	store(rdir, f, "");
	unLockFile();

	fclose(f);
	return NC_ERR_OK;
}
示例#5
0
void OriginLock::lock()
{
    m_mutex.lock();

#if USE(FILE_LOCK)
    m_lockHandle = openFile(m_lockFileName, OpenForWrite);
    if (m_lockHandle == invalidPlatformFileHandle) {
        // The only way we can get here is if the directory containing the lock
        // has been deleted or we were given a path to a non-existant directory.
        // In that case, there's nothing we can do but cleanup and return.
        m_mutex.unlock();
        return;
    }

    lockFile(m_lockHandle, LockExclusive);
#endif
}
示例#6
0
文件: startup.c 项目: DomChey/ptpd
int
writeLockFile(RunTimeOpts * rtOpts)
{

    int lockPid = 0;

    DBGV("Checking lock file: %s\n", rtOpts->lockFile);

    if ( (G_lockFilePointer=fopen(rtOpts->lockFile, "w+")) == NULL) {
        PERROR("Could not open lock file %s for writing", rtOpts->lockFile);
        return(0);
    }
    if (lockFile(fileno(G_lockFilePointer)) < 0) {
        if ( checkLockStatus(fileno(G_lockFilePointer),
                             DEFAULT_LOCKMODE, &lockPid) == 0) {
            ERROR("Another "PTPD_PROGNAME" instance is running: %s locked by PID %d\n",
                  rtOpts->lockFile, lockPid);
        } else {
            PERROR("Could not acquire lock on %s:", rtOpts->lockFile);
        }
        goto failure;
    }
    if(ftruncate(fileno(G_lockFilePointer), 0) == -1) {
        PERROR("Could not truncate %s: %s",
               rtOpts->lockFile, strerror(errno));
        goto failure;
    }
    if ( fprintf(G_lockFilePointer, "%ld\n", (long)getpid()) == -1) {
        PERROR("Could not write to lock file %s: %s",
               rtOpts->lockFile, strerror(errno));
        goto failure;
    }
    INFO("Successfully acquired lock on %s\n", rtOpts->lockFile);
    fflush(G_lockFilePointer);
    return(1);
failure:
    fclose(G_lockFilePointer);
    return(0);

}
示例#7
0
void daemonize(QString directory, Logger *LOG){
    int i;
    char str[10];
    if(getppid()==1)
        return; // déjà un deamon

    /*
    i=fork();
    if (i<0){// fork error
        LOG->error(QObject::tr("Fork error"));
        exit(EXIT_FAILURE);
    }
    if (i>0)// parent /
        exit(EXIT_SUCCESS);


    // Enfant
    setsid(); //Nouveau process group
    */
   // for (i=getdtablesize();i>=0;--i) close(i); // Fermeture de tous les descripteur
   //     i=open("/dev/null",O_RDWR); dup(i); dup(i); // gestion de l'entrée/sortie standard

    umask(027);

    chdir(directory.toStdString().c_str()); //Changement de repertoire d'execution
    sprintf(str,"%d\n",getpid());
    QFile lockFile(lockFilePathGlob);
    lockFile.open(QIODevice::ReadWrite);
    if (lockFile.write(str)<0){
        LOG->error(QObject::tr("Error while opening lock file : ")+QString(lockFilePathGlob));
        exit(EXIT_FAILURE);
    }
    lockFile.close();

    signal(SIGTERM,signal_handler); //Gestion du SIGTERM
    signal(SIGKILL,signal_handler); //Gestion du SIGTERM
    signal(SIGSEGV,signal_handler); //Gestion du SIGSEGV
}
示例#8
0
文件: nxml.cpp 项目: TitanNit/tdt
int NConfig::fromXML(const char *filename, int force)
{
	if (fd < 0)
		return NC_ERR_NFILE;
	if (omode != NC_O_RW)
		return NC_ERR_PERM;
#ifndef HAVE_LIBXML2
	return NC_ERR_NOSUPPORT;
#else
	struct ncParseState state = { noRoot, noRoot, NULL, 0, 0, force, this };
	sh.getEntity = ncXmlGetEntity;
	sh.startElement = ncXmlStartElement;
	sh.endElement = ncXmlEndElement;

	lockFile(NC_L_RW);
	cdir = rdir;
	int ret = ncXmlSAXParseFile(&sh, &state, filename);
	cdir = rdir;
	unLockFile();

	return ret < 0 ? NC_ERR_NVAL : NC_ERR_OK;
#endif /* HAVE_LIBXML2 */
}
示例#9
0
文件: file.c 项目: Feechka/UOBP
int
attemptFileLock (int file, int exclusive) {
  return lockFile(file, exclusive, 0);
}
示例#10
0
文件: file.c 项目: Feechka/UOBP
int
acquireFileLock (int file, int exclusive) {
  return lockFile(file, exclusive, 1);
}
示例#11
0
bool DatabaseTabWidget::saveDatabaseAs(Database* db)
{
    DatabaseManagerStruct& dbStruct = m_dbList[db];
    QString oldFileName;
    if (dbStruct.saveToFilename) {
        oldFileName = dbStruct.filePath;
    }
    else {
        oldFileName = tr("New database").append(".kdbx");
    }
    QString fileName = fileDialog()->getSaveFileName(this, tr("Save database as"),
                                                     oldFileName, tr("KeePass 2 Database").append(" (*.kdbx)"),
                                                     nullptr, 0, "kdbx");
    if (!fileName.isEmpty()) {
        QFileInfo fileInfo(fileName);
        QString lockFilePath;
        if (fileInfo.exists()) {
            // returns empty string when file doesn't exist
            lockFilePath = fileInfo.canonicalPath();
        }
        else {
            lockFilePath = fileInfo.absolutePath();
        }
        QString lockFileName = QString("%1/.%2.lock").arg(lockFilePath, fileInfo.fileName());
        QScopedPointer<QLockFile> lockFile(new QLockFile(lockFileName));
        lockFile->setStaleLockTime(0);
        if (!lockFile->tryLock()) {
            // for now silently ignore if we can't create a lock file
            // due to lack of permissions
            if (lockFile->error() != QLockFile::PermissionError) {
                QMessageBox::StandardButton result = MessageBox::question(this, tr("Save database as"),
                    tr("The database you are trying to save as is locked by another instance of KeePassX.\n"
                       "Do you want to save it anyway?"),
                    QMessageBox::Yes | QMessageBox::No);

                if (result == QMessageBox::No) {
                    return false;
                }
                else {
                    // take over the lock file if possible
                    if (lockFile->removeStaleLockFile()) {
                        lockFile->tryLock();
                    }
                }
            }
        }

        QSaveFile saveFile(fileName);
        if (!saveFile.open(QIODevice::WriteOnly)) {
            MessageBox::critical(this, tr("Error"), tr("Writing the database failed.") + "\n\n"
                                 + saveFile.errorString());
            return false;
        }

        m_writer.writeDatabase(&saveFile, db);
        if (m_writer.hasError()) {
            MessageBox::critical(this, tr("Error"), tr("Writing the database failed.") + "\n\n"
                                 + m_writer.errorString());
            return false;
        }
        if (!saveFile.commit()) {
            MessageBox::critical(this, tr("Error"), tr("Writing the database failed.") + "\n\n"
                                 + saveFile.errorString());
            return false;
        }

        dbStruct.modified = false;
        dbStruct.saveToFilename = true;
        dbStruct.readOnly = false;
        dbStruct.filePath = fileInfo.absoluteFilePath();
        dbStruct.canonicalFilePath = fileInfo.canonicalFilePath();
        dbStruct.fileName = fileInfo.fileName();
        dbStruct.dbWidget->updateFilename(dbStruct.filePath);
        delete dbStruct.lockFile;
        dbStruct.lockFile = lockFile.take();
        updateTabName(db);
        updateLastDatabases(dbStruct.filePath);
        return true;
    }
    else {
        return false;
    }
}
示例#12
0
void KConfigINIBackEnd::sync(bool bMerge)
{
    // write-sync is only necessary if there are dirty entries
    if(!pConfig->isDirty())
        return;

    bool bEntriesLeft = true;

    // find out the file to write to (most specific writable file)
    // try local app-specific file first

    if(!mfileName.isEmpty())
    {
        // Create the containing dir if needed
        if((resType != "config") && !QDir::isRelativePath(mLocalFileName))
        {
            KURL path;
            path.setPath(mLocalFileName);
            QString dir = path.directory();
            KStandardDirs::makeDir(dir);
        }

        // Can we allow the write? We can, if the program
        // doesn't run SUID. But if it runs SUID, we must
        // check if the user would be allowed to write if
        // it wasn't SUID.
        if(checkAccess(mLocalFileName, W_OK))
        {
            // File is writable
            KLockFile::Ptr lf;

            bool mergeLocalFile = bMerge;
            // Check if the file has been updated since.
            if(mergeLocalFile)
            {
                lf = lockFile(false); // Lock file for local file
                if(lf && lf->isLocked())
                    lf = 0; // Already locked, we don't need to lock/unlock again

                if(lf)
                {
                    lf->lock(KLockFile::LockForce);
                    // But what if the locking failed? Ignore it for now...
                }

                QFileInfo info(mLocalFileName);
                if((d->localLastSize == info.size()) && (d->localLastModified == info.lastModified()))
                {
                    // Not changed, don't merge.
                    mergeLocalFile = false;
                }
                else
                {
                    // Changed...
                    d->localLastModified = QDateTime();
                    d->localLastSize = 0;
                }
            }

            bEntriesLeft = writeConfigFile(mLocalFileName, false, mergeLocalFile);

            // Only if we didn't have to merge anything can we use our in-memory state
            // the next time around. Otherwise the config-file may contain entries
            // that are different from our in-memory state which means we will have to
            // do a merge from then on.
            // We do not automatically update the in-memory state with the on-disk
            // state when writing the config to disk. We only do so when
            // KCOnfig::reparseConfiguration() is called.
            // For KDE 4.0 we may wish to reconsider that.
            if(!mergeLocalFile)
            {
                QFileInfo info(mLocalFileName);
                d->localLastModified = info.lastModified();
                d->localLastSize = info.size();
            }
            if(lf)
                lf->unlock();
        }
    }

    // only write out entries to the kdeglobals file if there are any
    // entries marked global (indicated by bEntriesLeft) and
    // the useKDEGlobals flag is set.
    if(bEntriesLeft && useKDEGlobals)
    {

        // can we allow the write? (see above)
        if(checkAccess(mGlobalFileName, W_OK))
        {
            KLockFile::Ptr lf = lockFile(true); // Lock file for global file
            if(lf && lf->isLocked())
                lf = 0; // Already locked, we don't need to lock/unlock again

            if(lf)
            {
                lf->lock(KLockFile::LockForce);
                // But what if the locking failed? Ignore it for now...
            }
            writeConfigFile(mGlobalFileName, true, bMerge); // Always merge
            if(lf)
                lf->unlock();
        }
    }
}
示例#13
0
int GuiLoader::openGUI(int argc, char *argv[]) {

	QManagedApplication a(argc, argv);

	QMessageBox msgBox;

	std::string lockFilePath = ColorKeeperModel::getLockFilePath("lock");
	LockServer server;
	if (!server.isServerUp() ) {
		msgBox.setText(
				"ColorKeeper is already running (have a look in your sys tray).<br>If you're sure ColorKeeper isn't running (may happen in case of session crash),<br>you'll find some help in the <a href=https://sites.google.com/a/mikrosimage.eu/colortribe/trouble-shootings>trouble-shootings section on ColorTribe web site. ");
		msgBox.exec();
		exit(1);
	}
	QFile lockFile(QString::fromStdString(lockFilePath));
	if (lockFile.open(QIODevice::WriteOnly))
		lockFile.close();
	ColorKeeperModel::shouldDelete = true;

	if (!QSystemTrayIcon::isSystemTrayAvailable()) {
		msgBox.setText(
				"I couldn't detect any system tray and ColorKeeper needs one.<br>Please check if you didn't remove it.<br>You'll find some help in the <a href=https://sites.google.com/a/mikrosimage.eu/colortribe/trouble-shootings>trouble-shootings section on ColorTribe web site</a>.");
		msgBox.exec();
		exit(1);
	}

	QApplication::setQuitOnLastWindowClosed(false);
	QPixmap pixmap("./img/splash.png");
	QSplashScreen splash(pixmap);
	splash.show();
	QString message = "Version ";
	message.append(QString::number(ColorKeeperModel::version_major));
	message.append(QString(ColorKeeperModel::version_minor.c_str()));

	splash.showMessage(message, Qt::AlignBottom | Qt::AlignLeft, QColor(255,
			255, 255));

	QKeeperMainWindow mainWin(a);

	a.processEvents();

#ifdef __APPLE__
	QFile file("style/macOSStyle.qss");
#else
	QFile file("style/style.qss");
#endif
	if (file.open(QIODevice::ReadOnly)) {
		// Applique la CSS a la fenetre Qt
		QString styleSheet = QLatin1String(file.readAll());
		a.setStyleSheet(styleSheet);
		mainWin.setStyleSheet(styleSheet);
		file.close();
	}

	//mainWin.show();
	splash.finish(&mainWin);

	QCoreApplication::setOrganizationName("HD3D");
	QCoreApplication::setApplicationName("ColorKeeper");

	//	QString path = QCoreApplication::applicationDirPath() ;
	//	path.append("/../PlugIns");
	//QCoreApplication::addLibraryPath(path);
	//QCoreApplicatop,

	_isLoaded = true;

	ColorKeeperModel::Instance().sendAMailCalibrationRequest();
	return a.exec();

}
示例#14
0
bool KMailBox::isLocked() const
{
	QFileInfo lockFile(_file + QString(".lock"));

	return lockFile.exists();
}
示例#15
0
/**
 * Main Automessage menu.  Displays the auto message then queries for input.
 */
void do_automessage() {
  std::stringstream lockFileStream;
  lockFileStream << syscfg.gfilesdir << LOCKAUTO_MSG;
  std::string automessageLockFile = lockFileStream.str();

  std::stringstream autoMessageStream;
  autoMessageStream << syscfg.gfilesdir << AUTO_MSG;
  std::string autoMessageFile = autoMessageStream.str();

  // initally show the auto message
  read_automessage();

  bool done = false;
  do {
    GetSession()->bout.NewLine();
    char cmdKey = ShowAMsgMenuAndGetInput(automessageLockFile);
    switch (cmdKey) {
    case 'Q':
      done = true;
      break;
    case 'R':
      read_automessage();
      break;
    case 'W':
      write_automessage();
      break;
    case 'A': {
      grab_quotes(NULL, NULL);
      WStatus *pStatus = GetApplication()->GetStatusManager()->GetStatus();
      if (pStatus->GetAutoMessageAuthorUserNumber() > 0) {
        strcpy(irt, "Re: AutoMessage");
        email(pStatus->GetAutoMessageAuthorUserNumber(), 0, false, pStatus->IsAutoMessageAnonymous() ? anony_sender : 0);
      }
      delete pStatus;
    }
    break;
    case 'D':
      GetSession()->bout << "\r\n|#3Delete Auto-message, Are you sure? ";
      if (yesno()) {
        WFile::Remove(autoMessageFile);
      }
      GetSession()->bout.NewLine(2);
      break;
    case 'L':
      if (WFile::Exists(automessageLockFile)) {
        GetSession()->bout << "\r\n|#3Message is already locked.\r\n\n";
      } else {
        GetSession()->bout <<  "|#9Do you want to lock the Auto-message? ";
        if (yesno()) {
          /////////////////////////////////////////////////////////
          // This makes a file in your GFILES dir 1 bytes long,
          // to tell the board if it is locked or not. It consists
          // of a space.
          //
          WTextFile lockFile(automessageLockFile, "w+t");
          lockFile.WriteChar(' ');
          lockFile.Close();
        }
      }
      break;
    case 'U':
      if (!WFile::Exists(automessageLockFile)) {
        GetSession()->bout << "Message not locked.\r\n";
      } else {
        GetSession()->bout << "|#5Unlock message? ";
        if (yesno()) {
          WFile::Remove(automessageLockFile);
        }
      }
      break;
    }
  } while (!done && !hangup);
}
QString GRASS_EXPORT QgsGrass::openMapset( QString gisdbase, QString location, QString mapset )
{
  QgsDebugMsg( QString( "gisdbase = %1" ).arg( gisdbase.toUtf8().constData() ) );
  QgsDebugMsg( QString( "location = %1" ).arg( location.toUtf8().constData() ) );
  QgsDebugMsg( QString( "mapset = %1" ).arg( mapset.toUtf8().constData() ) );

  QString mapsetPath = gisdbase + "/" + location + "/" + mapset;

  // Check if the mapset is in use
  QString gisBase = getenv( "GISBASE" );
  if ( gisBase.isEmpty() ) return QObject::tr( "GISBASE is not set." );

  QFileInfo fi( mapsetPath + "/WIND" );
  if ( !fi.exists() )
  {
    return QObject::tr( "%1 is not a GRASS mapset." ).arg( mapsetPath );
  }
  QString lock = mapsetPath + "/.gislock";

#ifndef _MSC_VER
  int pid = getpid();
#else
  int pid = GetCurrentProcessId();
#endif

  QgsDebugMsg( QString( "pid = %1" ).arg( pid ) );

#ifndef Q_OS_WIN
  QFile lockFile( lock );
  QProcess *process = new QProcess();
  QString lockProgram( gisBase + "/etc/lock" );

  QgsDebugMsg( QString( "pid = %1" ).arg( pid ) );

  process->start( lockProgram, QStringList() << lock << QString::number( pid ) );
  if ( !process->waitForStarted() )
  {
    delete process;
    return QObject::tr( "Cannot start %1/etc/lock" ).arg( gisBase );
  }

  process->waitForFinished( -1 );

  int status = process->exitStatus();
  QgsDebugMsg( QString( "status = %1" ).arg( status ) );
  delete process;

  if ( status > 0 )
    return QObject::tr( "Mapset is already in use." );
#endif // !WIN32

  // Create temporary directory
  QFileInfo info( mapsetPath );
  QString user = info.owner();

  mTmp = QDir::tempPath() + "/grass6-" + user + "-" + QString::number( pid );
  QDir dir( mTmp );
  if ( dir.exists() )
  {
    QFileInfo dirInfo( mTmp );
    if ( !dirInfo.isWritable() )
    {
#ifndef Q_OS_WIN
      lockFile.remove();
#endif
      return QObject::tr( "Temporary directory %1 exists but is not writable" ).arg( mTmp );
    }
  }
  else if ( !dir.mkdir( mTmp ) )
  {
#ifndef Q_OS_WIN
    lockFile.remove();
#endif
    return QObject::tr( "Cannot create temporary directory %1" ).arg( mTmp );
  }

  // Create GISRC file
  QString globalGisrc =  QDir::home().path() + "/.grassrc6";
  mGisrc = mTmp + "/gisrc";

  QgsDebugMsg( QString( "globalGisrc = %1" ).arg( globalGisrc ) );
  QgsDebugMsg( QString( "mGisrc = %1" ).arg( mGisrc ) );

  QFile out( mGisrc );
  if ( !out.open( QIODevice::WriteOnly ) )
  {
#ifndef Q_OS_WIN
    lockFile.remove();
#endif
    return QObject::tr( "Cannot create %1" ).arg( mGisrc );
  }
  QTextStream stream( &out );

  QFile in( globalGisrc );
  QString line;
  bool guiSet = false;
  char buf[1000];
  if ( in.open( QIODevice::ReadOnly ) )
  {
    while ( in.readLine( buf, 1000 ) != -1 )
    {
      line = buf;
      if ( line.contains( "GISDBASE:" ) ||
           line.contains( "LOCATION_NAME:" ) ||
           line.contains( "MAPSET:" ) )
      {
        continue;
      }
      if ( line.contains( "GRASS_GUI:" ) ) guiSet = true;
      stream << line;
    }
    in.close();
  }
  line = "GISDBASE: " + gisdbase + "\n";
  stream << line;
  line = "LOCATION_NAME: " + location + "\n";
  stream << line;
  line = "MAPSET: " + mapset + "\n";
  stream << line;
  if ( !guiSet )
  {
    stream << "GRASS_GUI: wxpython\n";
  }

  out.close();

  // Set GISRC environment variable

  /* _Correct_ putenv() implementation is not making copy! */
  putEnv( "GISRC", mGisrc );

  // Reinitialize GRASS
  G__setenv( "GISRC", mGisrc.toUtf8().data() );
#if defined(WIN32)
  G__setenv( "GISDBASE", shortPath( gisdbase ).toLocal8Bit().data() );
#else
  G__setenv( "GISDBASE", gisdbase.toUtf8().data() );
#endif
  G__setenv( "LOCATION_NAME", location.toLocal8Bit().data() );
  G__setenv( "MAPSET", mapset.toLocal8Bit().data() );
  defaultGisdbase = gisdbase;
  defaultLocation = location;
  defaultMapset = mapset;

  active = true;

#ifndef Q_OS_WIN
  // Close old mapset
  if ( mMapsetLock.length() > 0 )
  {
    QFile file( mMapsetLock );
    file.remove();
  }
#endif

  mMapsetLock = lock;

  return NULL;
}
// ######################################################################
void SimulationViewerStats::save1(const ModelComponentSaveInfo& sinfo)
{
  // Use a LINFO here since we are already slowed down by writing
  // stats, we should at least have a short debug on this fact
  LINFO("SAVING STATS TO %s",itsStatsFname.getVal().c_str());

  // Lock the file. We put this here to support multi-process in the
  // future. However, this will not work on NFS mounts.
  struct flock fl; int fd;
  lockFile(itsStatsFname.getVal().c_str(),fd,fl);

  // Since this is more or less debug info we open and flush every iteration.
  // rather than once each run.
  std::ofstream statsFile;
  statsFile.open(itsStatsFname.getVal().c_str(),std::ios_base::app);

  // get the OFS to save to, assuming sinfo is of type
  // SimModuleSaveInfo (will throw a fatal exception otherwise):
  nub::ref<FrameOstream> ofs =
    dynamic_cast<const SimModuleSaveInfo&>(sinfo).ofs;

  // also get the SimEventQueue:
  SimEventQueue *q    = dynamic_cast<const SimModuleSaveInfo&>(sinfo).q;

  // initialize our stats dump file if desired:
  if(itsFrameIdx == 0)
  {
    rutz::shared_ptr<SimReqVCXmaps> vcxm(new SimReqVCXmaps(this));
    q->request(vcxm); // VisualCortex is now filling-in the maps...

    if (itsStatsFname.getVal().size())
    {
      itsStatsFile = new std::ofstream(itsStatsFname.getVal().c_str());
      if (itsStatsFile->is_open() == false)
        LFATAL("Failed to open '%s' for writing.",
               itsStatsFname.getVal().c_str());

      // dump the settings of the model:
      getRootObject()->printout(*itsStatsFile, "# ");

      // list all our channels:
      //LFATAL("FIXME");
      // also get the SimEventQueue:

      rutz::shared_ptr<ChannelMaps> chm        = vcxm->channelmaps();
      uint                          numSubmaps = chm->numSubmaps();

      *itsStatsFile << "# CHANNELS: ";

      for(uint i = 0; i < numSubmaps; i++)
      {
        NamedImage<float> smap = chm->getRawCSmap(i);
        *itsStatsFile << smap.name() << ", ";
      }
      *itsStatsFile << std::endl;
    }
  }

  // We flush frequently since this output is debuggy in nature or it's being used
  // to collect information which needs assurance of accuracy for instance in
  // RSVP analysis. It is better to err on the side of caution.
  (*itsStatsFile).flush();
  (*itsStatsFile).close();

  // get the basic input frame info
  if (SeC<SimEventInputFrame> e = q->check<SimEventInputFrame>(this))
  {
    itsSizeX       = e->frame().getWidth();
    itsSizeY       = e->frame().getHeight();
    itsFrameNumber = (unsigned int)e->frameNum();
    itsFrameIdx    = itsFrameNumber;
  }
  else
  {
    itsFrameNumber = itsFrameIdx;
    itsFrameIdx++;
  }

  // get the latest input frame:
  // Since we are only using it's basic statistics (Height / Width) , we don't care about it's
  // blackboard status. Use SEQ_ANY then. Otherwise, this will not fetch at any rate.
  Image< PixRGB<byte> > input;
  if (SeC<SimEventRetinaImage> e = q->check<SimEventRetinaImage>(this,SEQ_ANY))
    input = e->frame().colorByte();
  else
    LINFO("No input? Check the SimEventCue.");

  // Get the current frame number or keep track on your own
  /*
  if (SeC<SimEventInputFrame> e = q->check<SimEventInputFrame>(this))
    itsFrameIdx = e->frameNum();
  else
    itsFrameIdx++;
  */

  // get the latest raw AGM:
  Image<float> agm;
  if (SeC<SimEventAttentionGuidanceMapOutput> e =
      q->check<SimEventAttentionGuidanceMapOutput>(this))
    agm = e->agm(1.0F);
  else
    LINFO("No AGM? Check the SimEventCue.");

  // if we are missing input or agm, return:
  // We also need to warn so that we know why the stats file may be empty
  bool quit = false;
  if (input.initialized() == false)
    {
      LINFO("WARNING!!! Input seems not to be initialized, so detailed stats cannot be saved.");
      quit = true;
    }
  if(agm.initialized() == false)
    {
      LINFO("WARNING!!! NO Attention Guidance MAP \"AGM\" so detailed stats cannot be saved.");
      quit = true;
    }

  if(quit == true) return;

  // update the trajectory:
  Image< PixRGB<byte> > res;
  const int w = input.getWidth();

  // save image results? if so let's prepare it
  if (itsSaveXcombo.getVal() || itsSaveYcombo.getVal())
    {
      Image<float> nagm = getMap(*q);
      res = colGreyCombo(input, nagm, itsSaveXcombo.getVal(),
                         itsDisplayInterp.getVal());
    }

  // if we are saving single channel stats save saliency stats using a compatable format
  // SEE: SingleChannel.C / saveStats(..) for more info on format
  if (itsGetSingleChannelStats.getVal())
    saveCompat(agm);

  // Save a bunch of stats?
  if (statsFile)
    {
      // start with the current simulation time:
       statsFile <<std::endl<<"= "<<q->now().msecs()
                     <<" # time of frame in ms"<<std::endl;

      // get min/max/avg and stdev and number of peaks in AGM:
      float mi, ma, av; getMinMaxAvg(agm, mi, ma, av);
      double sdev = stdev(agm);
      double peaksum; int npeaks = findPeaks(agm, 0.0f, 255.0f, peaksum);

      // find the location of max in the AGM, at scale of original input:
      float maxval; Point2D<int> maxloc;
      findMax(agm, maxloc, maxval);
      float scale = float(w) / float(agm.getWidth());
      maxloc.i = int(maxloc.i * scale + 0.4999F);
      maxloc.j = int(maxloc.j * scale + 0.4999F);
      if (res.initialized())
        {
          drawPatch(res, maxloc, 4, COL_YELLOW);
          drawPatch(res, maxloc + Point2D<int>(w, 0), 4, COL_YELLOW);
        }

      // find the location of min in the AGM, at scale of original input:
      float minval; Point2D<int> minloc;
      findMin(agm, minloc, minval);
      minloc.i = int(minloc.i * scale + 0.4999F);
      minloc.j = int(minloc.j * scale + 0.4999F);
      if (res.initialized())
        {
          drawPatch(res, minloc, 4, COL_GREEN);
          drawPatch(res, minloc + Point2D<int>(w, 0), 4, COL_GREEN);
        }

      // save some stats for that location:
       statsFile  <<maxloc.i<<' '<<maxloc.j<<' '<<minloc.i<<' '
                  <<minloc.j<<' '<<ma<<' '<<mi<<' '<<av<<' '<<sdev
                  <<' '<<npeaks<<' '<<peaksum
                  <<" # Xmax Ymax Xmin Ymin max min avg std npeaks peaksum"
                  <<std::endl;

      // build a vector of points where we will save samples. First is
      // the max, second the min, then a bunch of random locations:
      std::vector<Point2D<int> > loc;
      loc.push_back(maxloc);
      loc.push_back(minloc);
      for (uint n = 0; n < 100; n ++)
        loc.push_back(Point2D<int>(randomUpToNotIncluding(input.getWidth()),
                              randomUpToNotIncluding(input.getHeight())));

      // Get all the conspicuity maps:
      ImageSet<float> cmap;
      //LFATAL("FIXME");
      rutz::shared_ptr<SimReqVCXmaps> vcxm(new SimReqVCXmaps(this));
      q->request(vcxm); // VisualCortex is now filling-in the maps...
      rutz::shared_ptr<ChannelMaps> chm = vcxm->channelmaps();
      uint numSubmaps = chm->numSubmaps();
      for(uint i=0;i < numSubmaps; i++)
      {
        NamedImage<float> tempMap = chm->getRawCSmap(i);
        Image<float> m = tempMap;
        cmap.push_back(m);

        // also store sample points at the min/max locations:
        Point2D<int> p; float v;
        findMax(m, p, v); loc.push_back(p);
        findMin(m, p, v); loc.push_back(p);
      }
      /*
      for (uint i = 0; i < itsBrain->getVC()->numChans(); i ++)
        {
          Image<float> m = itsBrain->getVC()->subChan(i)->getOutput();
          cmap.push_back(m);

          // also store sample points at the min/max locations:
          Point2D<int> p; float v;
          findMax(m, p, v); loc.push_back(p);
          findMin(m, p, v); loc.push_back(p);
        }
      */

      // Go over all sample points and save feature map and
      // conspicuity map values at those locations:
      for (uint i = 0; i < loc.size(); i ++)
        {
          Point2D<int> p = loc[i];
          Point2D<int> pp(int(p.i / scale), int(p.j / scale));

           statsFile <<p.i<<' '<<p.j<<"     ";

          // do the conspicuity maps first. Since they are all at the
          // scale of the AGM, we use pp:
          for (uint j = 0; j < cmap.size(); j ++)
          {
            if((int(p.i / scale) < agm.getWidth()) &&
               (int(p.j / scale) < agm.getHeight()))
            {
              (statsFile)<<cmap[j].getVal(pp)<<' ';
              (statsFile)<<"    ";
            }
            else
            {
              (statsFile)<<"-1"<<' ';
              (statsFile)<<"    ";
            }
          }

          // now the feature maps, we use coordinates p:
          /* TOO BOGUS - disabled for now
          std::vector<double> f;
          itsBrain->getVC()->getFeatures(p, f);
          for (uint j = 0; j < f.size(); j ++) (*statsFile)<<f[j]<<' ';
          */

           statsFile  <<"# features "<<i<<" at ("<<p.i
                         <<", "<<p.j<<')'<<std::endl;
        }
  }

  statsFile.flush();
  statsFile.close();
  unlockFile(itsStatsFname.getVal().c_str(),fd,fl);
  // save results?
  if (res.initialized())
    ofs->writeRGB(res, "T",
                  FrameInfo("SimulationViewerStats trajectory", SRC_POS));

  // Should we compute attention gate stats
  // If we have AG stats we will save the basic LAM stats anyways
  if(itsComputeAGStats.getVal())
    computeAGStats(*q);
  else if (SeC<SimEventAttentionGateOutput> ag =
           q->check<SimEventAttentionGateOutput>(this))
    computeLAMStats(ag->lam());

  //! Save the overlap image
  if(itsOverlap.initialized())
    ofs->writeRGB(itsOverlap, "AG-STAT-MASK",
                  FrameInfo("Stats mask overlap", SRC_POS));

  if(itsVisualSegments.initialized())
    ofs->writeRGB(itsVisualSegments, "AG-STAT-SEGS",
                  FrameInfo("Stats segments", SRC_POS));

  if(itsVisualCandidates.initialized())
    ofs->writeGray(itsVisualCandidates, "AG-STAT-CAND",
                   FrameInfo("Stats candidates", SRC_POS));

}
示例#18
0
// ssl host port url
// ssl host port url file
// ssl host port url key file
// ssl host port url key file dir sec
int main(int ac, char *av[]) {
   bool dbg;
   SSL_CTX *ctx;
   SSL *ssl;
   int n, sec, getLen, lenLen, fd, sd;
   DIR *dp;
   struct dirent *p;
   struct stat st;
   char get[1024], buf[4096], nm[4096], len[64];

   if (dbg = strcmp(av[ac-1], "+") == 0)
      --ac;
   if (!(ac >= 4 && ac <= 6  ||  ac == 8))
      giveup("host port url [[key] file] | host port url key file dir sec");
   if (strlen(Get)+strlen(av[1])+strlen(av[2])+strlen(av[3]) >= sizeof(get))
      giveup("Names too long");
   getLen = sprintf(get, Get, av[3], av[1], av[2]);

   SSL_library_init();
   SSL_load_error_strings();
   if (!(ctx = SSL_CTX_new(SSLv23_client_method()))) {
      ERR_print_errors_fp(stderr);
      giveup("SSL init");
   }
   SSL_CTX_set_cipher_list(ctx, Ciphers);
   ssl = SSL_new(ctx);

   if (ac <= 6) {
      if (sslConnect(ssl, av[1], av[2]) < 0) {
         ERR_print_errors_fp(stderr);
         giveup("Can't connect");
      }
      if (SSL_write(ssl, get, getLen) < 0) {
         ERR_print_errors_fp(stderr);
         giveup("SSL GET");
      }
      if (ac > 4) {
         if (*av[4]  &&  !sslFile(ssl,av[4]))
            giveup(av[4]);
         if (ac > 5  &&  *av[5]  &&  !sslFile(ssl,av[5]))
            giveup(av[5]);
      }
      while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0)
         write(STDOUT_FILENO, buf, n);
      if (dbg)
         ERR_print_errors_fp(stderr);
      return 0;
   }
   if (!dbg) {
      signal(SIGCHLD,SIG_IGN);  /* Prevent zombies */
      if ((n = fork()) < 0)
         giveup("detach");
      if (n)
         return 0;
      setsid();
   }
   File = av[5];
   Dir = av[6];
   sec = atoi(av[7]);
   signal(SIGINT, doSigTerm);
   signal(SIGTERM, doSigTerm);
   signal(SIGPIPE, SIG_IGN);
   signal(SIGALRM, SIG_IGN);
   for (;;) {
      if (*File && (fd = open(File, O_RDWR)) >= 0) {
         if (fstat(fd,&st) < 0  ||  st.st_size == 0)
            close(fd);
         else {
            lockFile(fd);
            if (fstat(fd,&st) < 0  ||  (Size = st.st_size) == 0)
               giveup("Can't access");
            lenLen = sprintf(len, "%ld\n", Size);
            if ((Data = malloc(Size)) == NULL)
               giveup("Can't alloc");
            if (read(fd, Data, Size) != Size)
               giveup("Can't read");
            Hot = YES;
            if (ftruncate(fd,0) < 0)
               giveup("Can't truncate");
            close(fd);
            for (;;) {
               if ((sd = sslConnect(ssl, av[1], av[2])) >= 0) {
                  alarm(420);
                  if (SSL_write(ssl, get, getLen) == getLen  &&
                           (!*av[4] || sslFile(ssl,av[4]))  &&       // key
                           SSL_write(ssl, len, lenLen) == lenLen  && // length
                           SSL_write(ssl, Data, Size) == Size  &&    // data
                           SSL_write(ssl, "T", 1) == 1  &&           // ack
                           SSL_read(ssl, buf, 1) == 1  &&  buf[0] == 'T' ) {
                     Hot = NO;
                     alarm(0);
                     sslClose(ssl,sd);
                     break;
                  }
                  alarm(0);
                  sslClose(ssl,sd);
               }
               if (dbg)
                  ERR_print_errors_fp(stderr);
               sleep(sec);
            }
            free(Data);
         }
      }
      if (*Dir && (dp = opendir(Dir))) {
         while (p = readdir(dp)) {
            if (p->d_name[0] != '.') {
               snprintf(nm, sizeof(nm), "%s%s", Dir, p->d_name);
               if ((n = readlink(nm, buf, sizeof(buf))) > 0  &&
                        (sd = sslConnect(ssl, av[1], av[2])) >= 0 ) {
                  if (SSL_write(ssl, get, getLen) == getLen  &&
                        (!*av[4] || sslFile(ssl,av[4]))  &&       // key
                        SSL_write(ssl, buf, n) == n  &&           // path
                        SSL_write(ssl, "\n", 1) == 1  &&          // nl
                        sslFile(ssl, nm) )                        // file
                     unlink(nm);
                  sslClose(ssl,sd);
               }
               if (dbg)
                  ERR_print_errors_fp(stderr);
            }
         }
         closedir(dp);
      }
      sleep(sec);
   }
}
示例#19
0
bool daemonIsRunning(QString lockFilePath){
    lockFilePathGlob = lockFilePath;
    QFile lockFile(lockFilePathGlob);
    return lockFile.exists();
}
示例#20
0
int NConfig::open(int how)
{
	if (!fname)
		return NC_ERR_NFILE;
	if (how != NC_O_RO && how != NC_O_RW)
		return NC_ERR_TYPE;
	if (fd > -1)
		close();

	int ff;
	if ((ff = ::open(fname, how)) == -1)
		return NC_ERR_PERM;

	struct stat sbuf;
	fstat(ff, &sbuf);

	if (!sbuf.st_size)
		return NC_ERR_CORRUPT;

#ifdef NO_MAP_SHARED
	if ((data = (char *) mmap(NULL, sbuf.st_size, how == NC_O_RO ? PROT_READ : (PROT_READ|PROT_WRITE), MAP_PRIVATE, ff, 0)) == MAP_FAILED) {
#else
	if ((data = (char *) mmap(NULL, sbuf.st_size, how == NC_O_RO ? PROT_READ : (PROT_READ|PROT_WRITE), MAP_SHARED, ff, 0)) == MAP_FAILED) {
#endif
		::close(ff);
		return NC_ERR_NMEM;
	}
	if (memcmp(((struct nc_sb_s *) data)->magic, NC_SB_MAGIC, 4)) {
		munmap(data, sbuf.st_size);
		::close(ff);
		return NC_ERR_CORRUPT;
	}
	fd = ff;
	omode = how;
	sb = SB;
	lsize = 0;
	cname = strdup("/");

	lockFile(NC_L_RO, TRUE);
	rdir = DE(sb->root);
	unLockFile();
	return NC_ERR_OK;
}

struct nc_de_s *NConfig::getDirEnt(const char *name, struct nc_de_s *cc)
{
	struct nc_de_s *ret = cc ? cc : ((*name == '/') ? rdir : cdir);
	char *c = canonize(name), *can;

	if (!(can = c))
		return ret;
	while (*c) {
		if (!strcmp(c, ".."))
			ret = DE(ret->parent);
		else
			if (strcmp(c, ".")) {
				struct nc_de_s *re = ret;
				int left = 0, right = ret->pages-1, p, r;

				ret = NULL;
				while (left <= right) {
					p = (left + right) / 2;
					r = strcmp(c, data+IDE(re, p)->name);
					if (r < 0) {
						left = p + 1;
						continue;
					}
					if (!r) {
						ret = IDE(re, p);
						break;
					}
					right = p - 1;
				}
			}
		c += strlen(c)+1;
		if (!ret || (*c && ret->type != NC_DIR)) {
			ret = NULL;
			break;
		}
	}
	free(can);
	return ret;
}

char *NConfig::canonize(const char *name)
{
	if (*name == '/')
		name++;
	size_t i = strlen(name);
	char *ret = (char *)calloc(1, i+3);
	memcpy(ret, name, i);
	for (size_t j=0; j<i; j++)
		if (ret[j] == '/')
			ret[j] = 0;
	return ret;
}

void NConfig::lockFile(int type, int force)
{
#ifdef NC_DEBUG_LOCK
	fprintf(stderr, "Lock called type=%d force=%d lock=%d olck=%u\n", type, force, lock, olck);
#endif
	if (lock == NC_L_RO && type == NC_L_RW) {
		fprintf(stderr, "Lock promotion is not possible.\n");
		abort();
	}
	if (lock != NC_L_NONE) {
		olck++;
		return;
	}
	
	struct flock flc = { type == NC_L_RW ? F_WRLCK : F_RDLCK, SEEK_SET, 0, 0, 0 };
	while (fcntl(fd, F_SETLKW, &flc)) {
		sched_yield();
		flc.l_type = type == NC_L_RW ? F_WRLCK : F_RDLCK;
		flc.l_whence = SEEK_SET;
		flc.l_len = flc.l_start = 0;
	}

#ifdef NC_DEBUG_LOCK
	fprintf(stderr, "Locked %u %u %s\n", sb->modtime, update, force ? "forced." : "");
#endif
	if (careful && type == NC_L_RW)
		mprotect(data, sb->size, PROT_READ | PROT_WRITE);
	lock = type;
	olck = 0;
	if (sb->modtime != update || force) {
		// refresh memory mapping
		if (lsize != sb->size) {
			_remap(lsize, sb->size);
			lsize = sb->size;
			chunks = CM(sb->chunk);
		}
		cdir = getDirEnt(cname);
		update = sb->modtime;
	}
}
示例#21
0
void freeLockFile(){
    QFile lockFile(lockFilePathGlob);
    lockFile.open(QIODevice::ReadWrite);
    lockFile.remove();
}
示例#22
0
KLockFile::LockResult KLockFile::lock(LockFlags options)
{
  if (d->isLocked)
     return KLockFile::LockOK;

  KLockFile::LockResult result;
  int hardErrors = 5;
  int n = 5;
  while(true)
  {
     KDE_struct_stat st_buf;
     result = lockFile(d->file, st_buf, d->linkCountSupport, d->componentData);
     if (result == KLockFile::LockOK)
     {
        d->staleTimer = QTime();
        break;
     }
     else if (result == KLockFile::LockError)
     {
        d->staleTimer = QTime();
        if (--hardErrors == 0)
        {
           break;
        }
     }
     else // KLockFile::Fail -- there is already such a file present (e.g. left by a crashed app)
     {
        if (!d->staleTimer.isNull() && d->statBuf != st_buf)
           d->staleTimer = QTime();

        if (d->staleTimer.isNull())
        {
           memcpy(&(d->statBuf), &st_buf, sizeof(KDE_struct_stat));
           d->staleTimer.start();

           d->pid = -1;
           d->hostname.clear();
           d->instance.clear();

           QFile file(d->file);
           if (file.open(QIODevice::ReadOnly))
           {
              QTextStream ts(&file);
              if (!ts.atEnd())
                 d->pid = ts.readLine().toInt();
              if (!ts.atEnd())
                 d->instance = ts.readLine();
              if (!ts.atEnd())
                 d->hostname = ts.readLine();
           }
        }

        bool isStale = false;
        if ((d->pid > 0) && !d->hostname.isEmpty())
        {
           // Check if hostname is us
           char hostname[256];
           hostname[0] = 0;
           gethostname(hostname, 255);
           hostname[255] = 0;

           if (d->hostname == QLatin1String(hostname))
           {
              // Check if pid still exists
              int res = ::kill(d->pid, 0);
              if ((res == -1) && (errno == ESRCH))
                 isStale = true;
           }
        }
        if (d->staleTimer.elapsed() > (d->staleTime*1000))
           isStale = true;

        if (isStale)
        {
           if ((options & ForceFlag) == 0)
              return KLockFile::LockStale;

           result = deleteStaleLock(d->file, d->statBuf, d->linkCountSupport, d->componentData);

           if (result == KLockFile::LockOK)
           {
              // Lock deletion successful
              d->staleTimer = QTime();
              continue; // Now try to get the new lock
           }
           else if (result != KLockFile::LockFail)
           {
              return result;
           }
        }
     }

     if (options & NoBlockFlag)
        break;

     struct timeval tv;
     tv.tv_sec = 0;
     tv.tv_usec = n*((KRandom::random() % 200)+100);
     if (n < 2000)
        n = n * 2;

     select(0, 0, 0, 0, &tv);
  }
  if (result == LockOK)
     d->isLocked = true;
  return result;
}