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


C++ QProcess::closeWriteChannel方法代码示例

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


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

示例1: MatchPersonRFID

int IDAService::MatchPersonRFID(QString rfid_info, QString timeout, QString db_name)
{
    QString app_name = "IDADesktopConsole.exe";
    QStringList arguments;
    arguments << "-m" << "MatchPersonRFID";
    arguments << "-u" << "NG";
    arguments << "-w" << app_dir+"/";
    arguments << "-d" << db_name;
    arguments << "-r" << rfid_info;

    QProcess proc;
    proc.start(app_name,arguments);

    // Wait for process start
    if(!proc.waitForStarted()){
        qDebug()<<"process start failed";
        emit MatchPersonRFIDFinished("NG");
        return 1;
    }

    // Close write channel because we do not need it
    proc.closeWriteChannel();

    QByteArray proc_output;
    while (false == proc.waitForFinished())
    {
       qDebug()<<"Process finish failed";
       emit MatchPersonRFIDFinished("NG");
       return 1;
    }

    proc_output = proc.readAll();
    qDebug()<<proc_output;
    //emit MatchPersonImageFinished(proc_output);
    emit MatchPersonRFIDFinished(proc_output);
    return 0;
}
开发者ID:hkutangyu,项目名称:IDA,代码行数:37,代码来源:idaservice.cpp

示例2: ShowAllUsername

int IDAService::ShowAllUsername(QString db_name)
{
    qDebug()<<"enter showAllUsername";
    QString app_name = "IDADesktopConsole.exe";
    QStringList arguments;
    arguments << "-m" << "ShowAllUsername";
    arguments << "-w" << app_dir+"/";
    arguments << "-d" << db_name;

    QProcess proc;
    proc.start(app_name,arguments);

    // Wait for process start
    if(!proc.waitForStarted()){
        qDebug()<<"process start failed";
        emit ShowAllUsernameFinished("NG");
        return 1;
    }

    // Close write channel because we do not need it
    proc.closeWriteChannel();

    QByteArray proc_output;
    while (false == proc.waitForFinished())
    {
       qDebug()<<"Process finish failed";
       emit ShowAllUsernameFinished(proc_output);
       return 1;
    }

    proc_output = proc.readAll();
    qDebug()<<proc_output;
     emit ShowAllUsernameFinished(proc_output);
    return 0;

}
开发者ID:hkutangyu,项目名称:IDA,代码行数:36,代码来源:idaservice.cpp

示例3: MatchPersonImage

int IDAService::MatchPersonImage(unsigned int image_index, float threshold, QString db_name)
{

    QString app_name = "IDADesktopConsole.exe";
    QStringList arguments;
    QString image_file_name = QString::number(image_index,10)+".bmp";
    arguments << "-m" << "MatchPersonImage";
    arguments << "-i" << image_file_name;
    arguments << "-u" << "NG";
    arguments << "-w" << app_dir+"/";
    arguments << "-d" << db_name;
    arguments << "-t" << QString::number((int)threshold,10);
    QProcess proc;
    proc.start(app_name,arguments);

    // Wait for process start
    if(!proc.waitForStarted()){
        qDebug()<<"process start failed";
        return 1;
    }

    // Close write channel because we do not need it
    proc.closeWriteChannel();

    QByteArray proc_output;
    while (false == proc.waitForFinished())
    {
       qDebug()<<"Process finish failed";
       return 1;
    }

    proc_output = proc.readAll();
    emit MatchPersonImageFinished(proc_output);
    qDebug()<<proc_output;
    return 0;
}
开发者ID:hkutangyu,项目名称:IDA,代码行数:36,代码来源:idaservice.cpp

示例4: executeSSH

bool SSHConnectionCLI::executeSSH(const QString& command,
                                  const QStringList& args, QString* stdout_str,
                                  QString* stderr_str, int* ec)
{
  QProcess proc;

  QStringList fullArgs;

  // Add username
  if (!m_user.isEmpty())
    fullArgs << "-l" << m_user;

  // Add port number
  fullArgs << "-p" << QString::number(m_port);

  // Add hostname
  fullArgs << m_host;

  // Add command and original arguments
  fullArgs << command;
  fullArgs << args;

  proc.start("ssh", fullArgs);
  int timeout_ms = 60000; // one minute

  if (!proc.waitForStarted(timeout_ms)) {
    qWarning() << QString("Failed to start ssh command with args \"%1\" "
                          "after %2 seconds.")
                    .arg(fullArgs.join(","))
                    .arg(timeout_ms / 1000);
    return false;
  }

  proc.closeWriteChannel();
  if (!proc.waitForFinished(timeout_ms)) {
    qWarning() << QString("ssh command with args \"%1\" failed to finish "
                          "within %2 seconds.")
                    .arg(fullArgs.join(","))
                    .arg(timeout_ms / 1000);
    return false;
  }

  if (proc.exitCode() == 255) {
    qWarning() << QString("ssh command with args \"%1\" returned an exit "
                          "code of 255. This usually means that ssh failed "
                          "to connect, but it may also be a valid exit code"
                          " for the command which was run. Assuming that "
                          "ssh has errored. Contact the development team "
                          "if you believe this is an error.")
                    .arg(fullArgs.join(","))
               << "\nstdout:\n"
               << QString(proc.readAllStandardOutput()) << "\nstderr:\n"
               << QString(proc.readAllStandardError());
    return false;
  }

  if (stdout_str != nullptr)
    *stdout_str = QString(proc.readAllStandardOutput());
  if (stderr_str != nullptr)
    *stderr_str = QString(proc.readAllStandardError());
  if (ec != nullptr)
    *ec = proc.exitCode();

  proc.close();

  return true;
}
开发者ID:xtalopt,项目名称:XtalOpt,代码行数:67,代码来源:sshconnection_cli.cpp

示例5: QString

bool CommandLineExporter::executeCommand
(
    const QString& command,
    const QString& inputFilePath,
    const QString& textInput,
    const QString& outputFilePath,
    QString& stdoutOutput,
    QString& stderrOutput
)
{
    QProcess process;
    process.setReadChannel(QProcess::StandardOutput);

    QString expandedCommand = command + QString(" ");

    if (!outputFilePath.isNull() && !outputFilePath.isEmpty())
    {
        // Redirect stdout to the output file path if the path variable wasn't
        // set in the command string.
        //
        if (!expandedCommand.contains(OUTPUT_FILE_PATH_VAR))
        {
            process.setStandardOutputFile(outputFilePath);
        }
        else
        {
            // Surround file path with quotes in case there are spaces in the
            // path.
            //
            QString outputFilePathWithQuotes = QString('\"') +
                outputFilePath + '\"';
            expandedCommand.replace(OUTPUT_FILE_PATH_VAR, outputFilePathWithQuotes);
        }
    }

    if
    (
        this->getSmartTypographyEnabled() &&
        !this->smartTypographyOnArgument.isNull()
    )
    {
        expandedCommand.replace
        (
            SMART_TYPOGRAPHY_ARG,
            smartTypographyOnArgument
        );
    }
    else if
    (
        !this->getSmartTypographyEnabled() &&
        !this->smartTypographyOffArgument.isNull()
    )
    {
        expandedCommand.replace
        (
            SMART_TYPOGRAPHY_ARG,
            smartTypographyOffArgument
        );
    }

    if (!inputFilePath.isNull() && !inputFilePath.isEmpty())
    {
        process.setWorkingDirectory(QFileInfo(inputFilePath).dir().path());
    }

    process.start(expandedCommand);

    if (!process.waitForStarted())
    {
        return false;
    }
    else
    {
        if (!textInput.isNull() && !textInput.isEmpty())
        {
            process.write(textInput.toUtf8());
            process.closeWriteChannel();
        }

        if (!process.waitForFinished())
        {
            return false;
        }
        else
        {
            stdoutOutput = QString::fromUtf8(process.readAllStandardOutput().data());
            stderrOutput = QString::fromUtf8(process.readAllStandardError().data());
        }
    }

    return true;
}
开发者ID:ThaiWood,项目名称:ghostwriter,代码行数:92,代码来源:CommandLineExporter.cpp

示例6: GetFilesystem

QString FsInfo::GetFilesystem( QString path )
{
    QProcess p;
#ifdef Q_WS_WIN
    bool ok = false;
    QString drive = ToWinPath( path, &ok );
    int colon = drive.indexOf( ":" );
    if( colon != 1 || !ok )
    {
		qCritical() << "FsInfo::GetFilesystem() colon != 1" << colon << ok;
		return QString();
    }
    drive.resize( 1 );

    p.start( "wmic", QStringList() << "/output:stdout" << "/interactive:off" << "/locale:ms_409" <<\
			 "logicaldisk" << "where" << "DeviceID=\'" + drive + ":\'" << "get" << "filesystem" );
#elif defined Q_WS_MAC
    p.start( "diskutil", QStringList() << "info" << path );
#else
    //try statfs first as it is the fastest.  but its descriptors are less than descriptive for ext variants
    struct statfs fInfo;
    int r = statfs( path.toLatin1().data(), &fInfo );
    if( !r )
    {
		switch( fInfo.f_type )
		{
		case MSDOS_SUPER_MAGIC:
			return "FAT";
			break;
		case NTFS_SB_MAGIC:
		case NTFS_PUNE_MAGIC:
			return "NTFS";
			break;
		case HFS_SUPER_MAGIC:
		case HPFS_SUPER_MAGIC:
			return "HPFS";
			break;
		default:
			break;
		}
    }
    p.start( "df", QStringList() << "-T" << path );
#endif
    if( !p.waitForStarted( 5000 ) )
    {
		qCritical() << "FsInfo::GetFilesystem failed to start";
		return QString();
    }
    p.closeWriteChannel();

    if( !p.waitForFinished() )
    {
		qCritical() << "!p.waitForFinished() ( getfs )";
		return QString();
    }
    if( p.exitCode() != QProcess::NormalExit )
    {
		qCritical() << "exit status ( getfs )" << p.exitCode();
		return QString();
    }

    QString output = p.readAll();
    output.remove( "\r" );
    QStringList list = output.split( "\n", QString::SkipEmptyParts );
#ifdef Q_WS_WIN
    if( !list.contains( "FileSystem  " ) || list.size() != 2 )
    {
		qCritical() << "wrong output ( getfs )" << list;
		return QString();
    }
    QString fs = list.at( 1 );
    fs = fs.simplified();
    return fs;
#elif defined Q_WS_MAC
    int size = list.size();
    for( int i = 0; i < size; i++ )
    {
		if( !list.at( i ).contains( "File System:" ) )
			continue;

		QString fs = list.at( i );
		fs.remove( 0, fs.indexOf( "File System:" ) + 12 );
		fs = fs.trimmed();
		int space = fs.indexOf( " " );
		if( space > 0 )
		{
			fs.remove( 0, space + 1 );
		}
		//qDebug() << fs;
		return fs;
    }
    return  QString();
#else
    int size = list.size();
    if( size != 2 )
    {
		qCritical() << "size != 2 ( getfs )" << list;
		return QString();
    }
    QString fs = list.at( 1 );
//.........这里部分代码省略.........
开发者ID:KarmA124,项目名称:qtwitgui,代码行数:101,代码来源:fsinfo.cpp

示例7: exec

bool EProcess::exec() {
  se = so = "";
  
  QMessageBox box;
  // We're not using a progressdialog, because we have no clue
  // how long things will take.
  QString allout;
  box.setWindowTitle("eln");
  box.setText(winCap);
  box.setWindowModality(Qt::ApplicationModal);
  box.setStandardButtons(QMessageBox::Cancel);
  box.show();
  QObject::connect(&box, SIGNAL(buttonClicked(QAbstractButton*)),
                   &box, SLOT(close()));
  QEventLoop el;
  QProcess process;
  if (!wd.isEmpty())
    process.setWorkingDirectory(wd);
  process.start(cmd, args);
  process.closeWriteChannel();
  if (!process.waitForStarted()) {
    QString msg = msgNoStart.isEmpty()
      ? "Could not start command: " + cmd
      : msgNoStart;
    se += msg + "\n";
    return false;
  }

  for (int ntimeouts=0; ntimeouts<10*300; ntimeouts++) {
    el.processEvents(); // this makes the messagebox show up
    if (process.waitForFinished(100)) {
      break; // success or failure
    }
    if (box.isHidden()) {
#ifdef Q_OS_LINUX
      ::kill(process.pid(), SIGINT);
      // Killing bzr with INT produces cleaner exit than with TERM...
#else
      process.kill();
      // ... but if we don't have POSIX, we have no choice.
#endif
      process.waitForFinished(500); // allow it some time to respond to signal
      break; // not good, but oh well
    }
    QString ste = process.readAllStandardError();
    allout += ste;
    se += ste;

    QString sto = process.readAllStandardOutput();
    allout += sto;
    so += sto;

    if (!ste.isEmpty() || !sto.isEmpty())
      box.setText(winCap + "\n" + allout);
  }

  QString ste = process.readAllStandardError();
  se += ste;
  
  QString sto = process.readAllStandardOutput();
  so += sto;

  se.replace(QRegExp("\\s*Traceback.*"), "");
  
  if (process.state()!=QProcess::NotRunning) {
    return false;
  }
  return process.exitStatus()==QProcess::NormalExit && process.exitCode()==0;
}
开发者ID:wagenadl,项目名称:eln,代码行数:69,代码来源:EProcess.cpp

示例8: extract

void ExternalExtractor::extract(ExtractionResult* result)
{
    Q_D(ExternalExtractor);

    QJsonDocument writeData;
    QJsonObject writeRootObject;
    QByteArray output;
    QByteArray errorOutput;

    writeRootObject[QStringLiteral("path")] = QJsonValue(result->inputUrl());
    writeRootObject[QStringLiteral("mimetype")] = result->inputMimetype();
    writeData.setObject(writeRootObject);

    QProcess extractorProcess;
    extractorProcess.start(d->mainPath, QIODevice::ReadWrite);
    extractorProcess.write(writeData.toJson());
    extractorProcess.closeWriteChannel();
    extractorProcess.waitForFinished(EXTRACTOR_TIMEOUT_MS);

    output = extractorProcess.readAll();
    errorOutput = extractorProcess.readAllStandardError();

    if (extractorProcess.exitStatus()) {
        qDebug() << errorOutput;
        return;
    }

    // now we read in the output (which is a standard json format) into the
    // ExtractionResult

    QJsonDocument extractorData = QJsonDocument::fromJson(output);
    if (!extractorData.isObject()) {
        return;
    }
    QJsonObject rootObject = extractorData.object();
    QJsonObject propertiesObject = rootObject[QStringLiteral("properties")].toObject();

    Q_FOREACH(auto key, propertiesObject.keys()) {
        if (key == QStringLiteral("typeInfo")) {
            TypeInfo info = TypeInfo::fromName(propertiesObject.value(key).toString());
            result->addType(info.type());
            continue;
        }

        // for plaintext extraction
        if (key == QStringLiteral("text")) {
            result->append(propertiesObject.value(key).toString(QStringLiteral("")));
            continue;
        }

        PropertyInfo info = PropertyInfo::fromName(key);
        if (info.name() != key) {
            continue;
        }
        result->add(info.property(), propertiesObject.value(key).toVariant());
    }

    if (rootObject[QStringLiteral("status")].toString() != QStringLiteral("OK")) {
        qDebug() << rootObject[QStringLiteral("error")].toString();
    }
}
开发者ID:KDE,项目名称:kfilemetadata,代码行数:61,代码来源:externalextractor.cpp

示例9: rebuildNoteEnml

/* Take the ENML note and transform it into HTML that WebKit will
  not complain about */
QByteArray EnmlFormatter::rebuildNoteEnml() {
    resources.clear();
    QByteArray b;
    qint32 index;

    content.replace("</input>","");

    // Strip off HTML header
    index = content.indexOf("<body");
    index = content.indexOf(">", index)+1;
    content.remove(0,index);
    index = content.indexOf("</body");
    content.truncate(index);
    b.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    b.append("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>\n");
    b.append("<html><head><title></title></head>");
    b.append("<body style=\"word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;\" >");
    b.append(content);
    b.append("</body></html>");
    content.clear();
    content = b;

    // Run it through "tidy".  It is a program which will fix any invalid HTML
    // and give us the results back through stdout.  In a perfect world this
    // wouldn't be needed, but WebKit doesn't always give back good HTML.
    QProcess tidyProcess;
    tidyProcess.start("tidy -raw -asxhtml -q -m -u -utf8 ", QIODevice::ReadWrite|QIODevice::Unbuffered);
    QLOG_DEBUG() << "Starting tidy " << tidyProcess.waitForStarted();
    tidyProcess.waitForStarted();
    tidyProcess.write(content);
    tidyProcess.closeWriteChannel();
    tidyProcess.waitForFinished();
    QLOG_DEBUG() << "Stopping tidy " << tidyProcess.waitForFinished() << " Return Code: " << tidyProcess.state();
    QLOG_DEBUG() << "Tidy Errors:" << tidyProcess.readAllStandardError();
    content.clear();
    content.append(tidyProcess.readAllStandardOutput());
    if (content == "") {
        formattingError = true;
        return "";
    }

    // Tidy puts this in place, but we don't really need it.
    content.replace("<form>", "");
    content.replace("</form>", "");

    index = content.indexOf("<body");
    content.remove(0,index);
    content.prepend("<style>img { height:auto; width:auto; max-height:auto; max-width:100%; }</style>");
    content.prepend("<head><meta http-equiv=\"content-type\" content=\"text-html; charset=utf-8\"></head>");
    content.prepend("<html>");
    content.append("</html>");
    content = fixEncryptionTags(content);

    QWebPage page;
    QEventLoop loop;
    page.mainFrame()->setContent(content);
    QObject::connect(&page, SIGNAL(loadFinished(bool)), &loop, SLOT(quit()));


    QWebElement element = page.mainFrame()->documentElement();
    QStringList tags = findAllTags(element);

    for (int i=0; i<tags.size(); i++) {
        QString tag = tags[i];
        QWebElementCollection anchors = page.mainFrame()->findAllElements(tag);
        foreach (QWebElement element, anchors) {
            if (element.tagName().toLower() == "input") {
                processTodo(element);
            } else if (element.tagName().toLower() == "a") {
                fixLinkNode(element);
            } else if (element.tagName().toLower() == "object") {
                fixObjectNode(element);
            } else if (element.tagName().toLower() == "img") {
                fixImgNode(element);
            } else if (!isElementValid(element.tagName()))
                element.removeFromDocument();
        }
    }
    content.clear();
    content.append(element.toOuterXml());

    // Strip off HTML header
    index = content.indexOf("<body");
    index = content.indexOf(">", index)+1;
    content.remove(0,index);
    index = content.indexOf("</body");
    content.truncate(index);
    b.clear();
    b.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    b.append("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>");
    b.append("<en-note style=\"word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;\" >");
    b.append(content);
    b.append("</en-note>");
    content.clear();
    content = b;

    postXmlFix();
    return content;
//.........这里部分代码省略.........
开发者ID:amareknight,项目名称:Nixnote2,代码行数:101,代码来源:enmlformatter.cpp

示例10: haproxy


//.........这里部分代码省略.........
        txtStream << "timeout server  30s\n";
        txtStream << "timeout connect 5s\n";
        txtStream << "errorfile 503 " + sibling_file_path + "provider.http\n";

        txtStream << "bind 127.0.0.1:8182\n";

        txtStream.seek(0);
        /*
        while(!txtStream.atEnd()){
            qDebug() << txtStream.readLine();
        }
        */
        file.close();

        QString command = "";
        #ifdef Q_OS_WIN
            command = "haproxy.exe -f haproxy.cfg";
            uint result = WinExec(qPrintable(command),SW_HIDE);            
            if (result < 31) {
                m_haproxyStatus = "Failed to launch haproxy (" + QString::number(result) + ") ";
                qDebug() << "Failed to launch haproxy (Windows): " + QString::number(result);
                return false;
            }
        #else
            QString haProxyPath = NULL;
            QString hasHaproxyExecutable = NULL;

            #if defined(Q_OS_MAC)
                // verify if the haproxy exist in Mac if not send an alert
                QFileInfo check_haproxy_exist_osx("/usr/local/bin/haproxy");
                check_haproxy_exist_osx.refresh();
                if (check_haproxy_exist_osx.exists()) {
                    haProxyPath = "/usr/local/bin/haproxy";
                } else {
                    m_haproxyStatus = "Failed: " + haProxyPath;
                    return false;
                }
            #else
                // try to find haproxy correctly
                QProcess shellProcess;

                // find for haproxy
                shellProcess.start("/bin/sh");
                shellProcess.write("which haproxy || whereis haproxy | cut -d ' ' -f 2");
                shellProcess.closeWriteChannel();
                shellProcess.waitForFinished(-1);
                haProxyPath = shellProcess.readAllStandardOutput().trimmed();

                // when you remove the haproxy from your computer that path still works
                if (haProxyPath == "/etc/haproxy") {
                    qDebug() << "HAProxy has only uninstall path ";
                    return false;
                }

                // verify if has haproxy executable
                command = "[ ! -e " + haProxyPath + " ]; echo $?";
                shellProcess.start("/bin/sh");
                shellProcess.write(qPrintable(command));
                shellProcess.closeWriteChannel();
                shellProcess.waitForFinished(-1);
                hasHaproxyExecutable = shellProcess.readAllStandardOutput().trimmed();

                if (hasHaproxyExecutable != "1") {
                    qDebug() << "HAProxy has no executable ";
                    return false;
                }
            #endif

            qDebug() << "HAProxy Path " << haProxyPath;

            // save in haproxy variable the path to show in dashboard
            Haproxy::m_haproxyPath = haProxyPath;

            // ha proxy location not found if output from command is empty or just the first word from whereis
            if (haProxyPath.isEmpty() || haProxyPath == "haproxy:") {
                qDebug() << "HAProxy not found!";
                 m_haproxyStatus = "NotFound: " + haProxyPath;
                return false;
            }

            //system("trap 'pkill -f haproxy; echo teste haproxy; exit;' INT TERM");
            command = haProxyPath + " -f " + sibling_file_path + "haproxy.cfg";
            int result = system(qPrintable(command));
            qDebug() << "Launched haproxy " << QString::number(result);
            if (result != 0) {
                m_haproxyStatus = "Failed to launch haproxy (" + QString::number(result) + ") " + haProxyPath + " " + sibling_file_path + "haproxy.cfg";
                return false;
            }
        #endif

        qDebug() << "Starting Haproxy: " << command;

    }
    else {
        m_haproxyStatus = "Failed to open (" + QString::number(file.error()) + ") " + sibling_file_path + "haproxy.cfg";
        qDebug() << "could not open the file";
        return false;
    }
    return true;
}
开发者ID:LetheanMovement,项目名称:lethean-gui,代码行数:101,代码来源:Haproxy.cpp

示例11: method_resizePartitions

bool InitDriveThread::method_resizePartitions()
{
    uint newStartOfRescuePartition = getFileContents(sysclassblock(_drive, 1)+"/start").trimmed().toUInt();
    uint newSizeOfRescuePartition  = sizeofBootFilesInKB()*1.024/1000 + 100;

    if (!umountSystemPartition())
    {
        emit error(tr("Error unmounting system partition."));
        return false;
    }

    if (!QFile::exists(partdev(_drive, 1)))
    {
        // SD card does not have a MBR.

        // Warn user that their SD card does not have an MBR and ask
        // if they would like us to create one for them
        QMessageBox::StandardButton answer;
        emit query(tr("Would you like NOOBS to create one for you?\nWARNING: This will erase all data on your SD card"),
                   tr("Error: No MBR present on SD Card"),
                   &answer);

        if(answer == QMessageBox::Yes)
        {
            emit statusUpdate(tr("Zeroing partition table"));
            if (!zeroMbr())
            {
                emit error(tr("Error zero'ing MBR/GPT. SD card may be broken or advertising wrong capacity."));
                return false;
            }

            // Create MBR containing single FAT partition
            emit statusUpdate(tr("Writing new MBR"));
            QProcess proc;
            proc.setProcessChannelMode(proc.MergedChannels);
            proc.start("/usr/sbin/parted "+_drive+" --script -- mktable msdos mkpartfs primary fat32 8192s -1");
            proc.waitForFinished(-1);
            if (proc.exitCode() != 0)
            {
                // Warn user if we failed to create an MBR on their card
                emit error(tr("Error creating MBR")+"\n"+proc.readAll());
                return false;
            }
            qDebug() << "Created missing MBR on SD card. parted output:" << proc.readAll();

            // Advise user that their SD card has now been formatted
            // suitably for installing NOOBS and that they will have to
            // re-copy the files before rebooting
            emit error(tr("SD card has now been formatted ready for NOOBS installation. Please re-copy the NOOBS files onto the card and reboot"));
            return false;
        }
        else
        {
            emit error(tr("SD card has not been formatted correctly. Please reformat using the SD Association Formatting Tool and try again."));
            return false;
        }

    }

    emit statusUpdate(tr("Removing partitions 2,3,4"));

    QFile f(_drive);
    f.open(f.ReadWrite);
    // Seek to partition entry 2
    f.seek(462);
    // Zero out partition 2,3,4 to prevent parted complaining about invalid constraints
    f.write(QByteArray(16*3, '\0'));
    f.flush();
    // Tell Linux to re-read the partition table
    ioctl(f.handle(), BLKRRPART);
    f.close();
    QThread::msleep(500);

    emit statusUpdate(tr("Resizing FAT partition"));

    /* Relocating the start of the FAT partition is a write intensive operation
     * only move it when it is not aligned on a MiB boundary already */
    if (newStartOfRescuePartition < 2048 || newStartOfRescuePartition % 2048 != 0)
    {
        newStartOfRescuePartition = PARTITION_ALIGNMENT; /* 4 MiB */
    }

    QString cmd = "/usr/sbin/parted --script "+_drive+" resize 1 "+QString::number(newStartOfRescuePartition)+"s "+QString::number(newSizeOfRescuePartition)+"M";
    qDebug() << "Executing" << cmd;
    QProcess p;
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    /* Suppress parted's big fat warning about its file system manipulation code not being robust.
       It distracts from any real error messages that may follow it. */
    env.insert("PARTED_SUPPRESS_FILE_SYSTEM_MANIPULATION_WARNING", "1");
    p.setProcessEnvironment(env);
    p.setProcessChannelMode(p.MergedChannels);
    p.start(cmd);
    p.closeWriteChannel();
    p.waitForFinished(-1);

    if (p.exitCode() != 0)
    {
        emit error(tr("Error resizing existing FAT partition")+"\n"+p.readAll());
        return false;
    }
//.........这里部分代码省略.........
开发者ID:XECDesign,项目名称:noobs,代码行数:101,代码来源:initdrivethread.cpp

示例12: _delete_encfs_m_point

Task::future<bool>& zuluMountTask::encfsMount( const QString& p,const QString& m,const QString& k,bool ro )
{
	return Task::run< bool >( [ p,m,k,ro ](){

		auto _encfsMount = [ & ](){

			auto _mount = [ & ](){

				QString exe ;

				if( ro ){

					exe = QString( "/usr/bin/encfs -S %1 %2 -o ro" ).arg( p,m ) ;
				}else{
					exe = QString( "/usr/bin/encfs -S %1 %2" ).arg( p,m ) ;
				}

				QProcess e ;

				e.start( exe ) ;
				e.waitForStarted() ;
				e.write( k.toLatin1() + '\n' ) ;

				e.closeWriteChannel() ;

				if( e.waitForFinished( 10000 ) ){

					return e.exitCode() == 0 ;
				}else{
					return false ;
				}
			} ;

			if( _create_encfs_mount_point( m ) ){

				if( _mount() ) {

					return true ;
				}else{
					return _delete_encfs_m_point( m ) ;
				}
			}else{
				return false ;
			}
		} ;

		QDir d( p ) ;

		QStringList l = d.entryList( QDir::Hidden | QDir::Files ) ;

		for( const auto& it : l ){

			if( it.startsWith( ".encfs" ) && it.endsWith( ".xml" ) ){

				/*
				 * encfs folders usually have a config hidden file name named ".encfs6.xml"
				 * and we assume the folder contains encfs files only if this file
				 * is present.
				 */

				return _encfsMount() ;
			}
		}

		return false ;
	} ) ;
}
开发者ID:joachimdostal,项目名称:zuluCrypt,代码行数:67,代码来源:zulumounttask.cpp

示例13: fillMediaInfo

bool MediaInfo::fillMediaInfo(const QString& path, MediaInfo& mediaInfo)
{
	QFileInfo file(path);
	QString width, height, len;
	QProcess ident;
	bool ok = true;
	bool audioEnc = false;

	QRegExp videoWidthRx("ID_VIDEO_WIDTH\\s*=\\s*(\\d+)");
	QRegExp videoHeightRx("ID_VIDEO_HEIGHT\\s*=\\s*(\\d+)");
	QRegExp lengthRx("ID_LENGTH\\s*=\\s*([\\d.]+)");
	QRegExp audioBitrateRx("ID_AUDIO_BITRATE\\s*=\\s*(\\d+)");
	QRegExp audioRateRx("ID_AUDIO_RATE\\s*=\\s*(\\d+)");
	QRegExp audioChannelsRx("ID_AUDIO_NCH\\s*=\\s*(\\d+)");

	QString audioEncLine("Opening audio decoder");

	if (!file.isFile())
		return false;

     ident.start(QString(MPLAYER_INDENTIFY).arg(file.absoluteFilePath()));
     if (!ident.waitForStarted())
         return false;

     ident.closeWriteChannel();
     if (!ident.waitForFinished())
         return false;

	 mediaInfo.fileSize = file.size();

	 mediaInfo.audioBitrate = -1;
	 mediaInfo.audioRate = -1;
	 mediaInfo.audioChannels = -1;

	 while (ident.canReadLine()) {
		 QString line = ident.readLine();

		 if (-1 != videoWidthRx.indexIn(line))
			 width = videoWidthRx.cap(1);
		 else if (-1 != videoHeightRx.indexIn(line))
			 height = videoHeightRx.cap(1);
		 else if (-1 != lengthRx.indexIn(line))
			 len = lengthRx.cap(1);
		 else if (!audioEnc && line.contains(audioEncLine))
			 audioEnc = true;
		 else if (audioEnc && -1 != audioBitrateRx.indexIn(line))
			 mediaInfo.audioBitrate = audioBitrateRx.cap(1).toInt(&ok);
		 else if (audioEnc && -1 != audioRateRx.indexIn(line))
			 mediaInfo.audioRate = audioRateRx.cap(1).toInt(&ok);
		 else if (audioEnc && -1 != audioChannelsRx.indexIn(line))
			 mediaInfo.audioChannels = audioChannelsRx.cap(1).toInt(&ok);

		 if (!ok)
			 return false;
	 }

	 if (!width.isEmpty() && !height.isEmpty())
		 mediaInfo.videoResolution = QString("%1x%2").arg(width).arg(height);
	 if (!len.isEmpty()) {
		 int secs = 0, msecs = 0;
		 QStringList lens = len.split(".");
		 if (!lens.size())
			 return false;
		 if (lens.size() > 0)
			 secs = lens[0].toInt(&ok);
		 if (lens.size() > 1)
			 msecs = lens[1].toInt(&ok);
		 if (!ok)
			 return false;

		 mediaInfo.duration = QString("%1:%2:%3:%4").
			 arg(secs / 3600,    2, 10, QChar('0')).
			 arg(secs / 60 % 60, 2, 10, QChar('0')).
			 arg(secs % 60,      2, 10, QChar('0')).
			 arg(msecs,          2, 10, QChar('0'));
	 }

	 return true;
}
开发者ID:rouming,项目名称:TvHolic,代码行数:79,代码来源:MediaInfo.cpp

示例14: main


//.........这里部分代码省略.........
			argsconc += "'rootcheck=no'";
#ifdef Q_OS_LINUX
			QString gksulocation = checkforgraphicalsu("gksu");
			if (gksulocation != "REQCNOTFOUND")
			{
				QProcess::startDetached(QString("%1 %2 %3").arg(gksulocation).arg(app.applicationFilePath()).arg(argsconc));
				return 0;
			}
			QString kdesulocation = checkforgraphicalsu("kdesu");
			if (kdesulocation != "REQCNOTFOUND")
			{
				QProcess::startDetached(QString("%1 %2 %3").arg(kdesulocation).arg(app.applicationFilePath()).arg(argsconc));
				return 0;
			}
			QString gnomesulocation = checkforgraphicalsu("gnomesu");
			if (gnomesulocation != "REQCNOTFOUND")
			{
				QProcess::startDetached(QString("%1 %2 %3").arg(gnomesulocation).arg(app.applicationFilePath()).arg(argsconc));
				return 0;
			}
			QString kdesudolocation = checkforgraphicalsu("kdesudo");
			if (kdesudolocation != "REQCNOTFOUND")
			{
				QProcess::startDetached(QString("%1 %2 %3").arg(kdesudolocation).arg(app.applicationFilePath()).arg(argsconc));
				return 0;
			}
			QMessageBox rootmsgb;
			rootmsgb.setIcon(QMessageBox::Warning);
			rootmsgb.setWindowTitle(uninstaller::tr("Must run as root"));
			rootmsgb.setTextFormat(Qt::RichText);
			rootmsgb.setText(uninstaller::tr("%2 must be run as root. Close it, and re-run using either:<br/><b>sudo %1</b><br/>or:<br/><b>su - -c '%1'</b>").arg(app.applicationFilePath()).arg(UNETBOOTINB));
			rootmsgb.setStandardButtons(QMessageBox::Ok);
			switch (rootmsgb.exec())
			{
				case QMessageBox::Ok:
					break;
				default:
					break;
			}
#endif
#ifdef Q_OS_MAC
			QProcess osascriptProc;
			osascriptProc.start("osascript");
			osascriptProc.write(QString("do shell script \""+app.applicationFilePath()+"\" with administrator privileges\n").toAscii().data());
			osascriptProc.closeWriteChannel();
			osascriptProc.waitForFinished(-1);
			return 0;
#endif
		}
	}
	#endif
	#ifdef Q_OS_WIN32
	QSettings chkinst("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\UNetbootin", QSettings::NativeFormat);
	#endif
	#ifdef Q_OS_LINUX
	QSettings chkinst(QSettings::SystemScope, "UNetbootin");
	#endif
#ifndef Q_OS_MAC
	if (chkinst.contains("Location"))
	{
		QMessageBox uninstmsgb;
		uninstmsgb.setIcon(QMessageBox::Information);
		uninstmsgb.setWindowTitle(uninstaller::tr("%1 Uninstaller").arg(UNETBOOTINB));
		uninstmsgb.setText(uninstaller::tr("%1 is currently installed. Remove the existing version?").arg(UNETBOOTINB));
 		uninstmsgb.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
 		switch (uninstmsgb.exec())
 		{
 			case QMessageBox::Ok:
 			{
 				ubnUninst();
			}
			case QMessageBox::Cancel:
				break;
	 		default:
				break;
 		}
		return 0;
	}
#endif
	unetbootin unetbootin;
	unetbootin.appNlang = tnapplang;
	unetbootin.appDir = QDir::toNativeSeparators(QString("%1/").arg(app.applicationDirPath()));
	unetbootin.appLoc = app.applicationFilePath();
	QIcon icon;
	icon.addFile(":/unetbootin_16.png", QSize(16,16));
	icon.addFile(":/unetbootin_22.png", QSize(22,22));
	icon.addFile(":/unetbootin_24.png", QSize(24,24));
	icon.addFile(":/unetbootin_32.png", QSize(32,32));
	icon.addFile(":/unetbootin_48.png", QSize(48,48));
#ifdef Q_OS_LINUX
	icon.addFile("/usr/share/pixmaps/unetbootin.png");
#endif
	unetbootin.setWindowIcon(icon);
	QObject::connect(&app, SIGNAL(lastWindowClosed()), &unetbootin, SLOT(killApplication()));
	bool automate = unetbootin.ubninitialize(oppairs);
	unetbootin.show();
	if (automate)
		QTimer::singleShot(0, &unetbootin, SLOT(on_okbutton_clicked()));
	return app.exec();
}
开发者ID:matsimon,项目名称:unetbootin-debian,代码行数:101,代码来源:main.cpp

示例15: import


//.........这里部分代码省略.........
              noDataValue = std::numeric_limits<double>::max() * -1.0;
              break;
            default: // should not happen
              noDataValue = std::numeric_limits<double>::max() * -1.0;
          }
          for ( qgssize i = 0; i < ( qgssize )block->width()*block->height(); i++ )
          {
            if ( block->isNoData( i ) )
            {
              block->setValue( i, noDataValue );
            }
          }
        }

        char * data = block->bits( row, 0 );
        int size = iterCols * block->dataTypeSize();
        QByteArray byteArray = QByteArray::fromRawData( data, size ); // does not copy data and does not take ownership
        if ( isCanceled() )
        {
          outStream << true; // cancel module
          break;
        }
        outStream << false; // not canceled
        outStream << noDataValue;

        outStream << byteArray;

        // Without waitForBytesWritten() it does not finish ok on Windows (process timeout)
        process->waitForBytesWritten( -1 );

#ifndef Q_OS_WIN
        // wait until the row is written to allow quick cancel (don't send data to buffer)
        process->waitForReadyRead();
        bool result;
        outStream >> result;
#endif
      }
      delete block;
      if ( isCanceled() )
      {
        outStream << true; // cancel module
        break;
      }
    }

    // TODO: send something back from module and read it here to close map correctly in module

    process->closeWriteChannel();
    // TODO: best timeout?
    process->waitForFinished( 30000 );

    QString stdoutString = process->readAllStandardOutput().data();
    QString stderrString = process->readAllStandardError().data();

    QString processResult = QString( "exitStatus=%1, exitCode=%2, error=%3, errorString=%4 stdout=%5, stderr=%6" )
                            .arg( process->exitStatus() ).arg( process->exitCode() )
                            .arg( process->error() ).arg( process->errorString() )
                            .arg( stdoutString.replace( "\n", ", " ) ).arg( stderrString.replace( "\n", ", " ) );
    QgsDebugMsg( "processResult: " + processResult );

    if ( process->exitStatus() != QProcess::NormalExit )
    {
      setError( process->errorString() );
      delete process;
      return false;
    }

    if ( process->exitCode() != 0 )
    {
      setError( stderrString );
      delete process;
      return false;
    }

    delete process;
  }
  QgsDebugMsg( QString( "redBand = %1 greenBand = %2 blueBand = %3" ).arg( redBand ).arg( greenBand ).arg( blueBand ) );
  if ( redBand > 0 && greenBand > 0 && blueBand > 0 )
  {
    // TODO: check if the group exists
    // I_find_group()
    QString name = mGrassObject.name();

    G_TRY
    {
      QgsGrass::setMapset( mGrassObject.gisdbase(), mGrassObject.location(), mGrassObject.mapset() );
      struct Ref ref;
      I_get_group_ref( name.toUtf8().data(), &ref );
      QString redName = name + QString( ".%1" ).arg( redBand );
      QString greenName = name + QString( ".%1" ).arg( greenBand );
      QString blueName = name + QString( ".%1" ).arg( blueBand );
      I_add_file_to_group_ref( redName.toUtf8().data(), mGrassObject.mapset().toUtf8().data(), &ref );
      I_add_file_to_group_ref( greenName.toUtf8().data(), mGrassObject.mapset().toUtf8().data(), &ref );
      I_add_file_to_group_ref( blueName.toUtf8().data(), mGrassObject.mapset().toUtf8().data(), &ref );
      I_put_group_ref( name.toUtf8().data(), &ref );
    }
    G_CATCH( QgsGrass::Exception &e )
    {
      QgsDebugMsg( QString( "Cannot create group: %1" ).arg( e.what() ) );
    }
开发者ID:sogis,项目名称:Quantum-GIS,代码行数:101,代码来源:qgsgrassimport.cpp


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