本文整理汇总了C++中QProcess类的典型用法代码示例。如果您正苦于以下问题:C++ QProcess类的具体用法?C++ QProcess怎么用?C++ QProcess使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QProcess类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: QProcess
/*
* Opens a terminal based on your DE.
*/
void WMHelper::openTerminal(const QString& dirName){
QProcess *p = new QProcess(qApp->activeWindow());
QStringList s;
QFileInfo f(dirName);
if (f.exists()){
if(isXFCERunning() && UnixCommand::hasTheExecutable(ctn_XFCE_TERMINAL)){
s << "--working-directory=" + dirName;
p->startDetached( ctn_XFCE_TERMINAL, s );
}
else if (isKDERunning() && UnixCommand::hasTheExecutable(ctn_KDE_TERMINAL)){
s << "--workdir";
s << dirName;
if (UnixCommand::isRootRunning())
{
p->startDetached( "dbus-launch " + ctn_KDE_TERMINAL + " --workdir " + dirName);
}
else
{
p->startDetached( ctn_KDE_TERMINAL, s );
}
}
else if (isTDERunning() && UnixCommand::hasTheExecutable(ctn_TDE_TERMINAL)){
s << "--workdir";
s << dirName;
p->startDetached( ctn_TDE_TERMINAL, s );
}
else if (isLXDERunning() && UnixCommand::hasTheExecutable(ctn_LXDE_TERMINAL)){
s << "--working-directory=" + dirName;
p->startDetached( ctn_LXDE_TERMINAL, s );
}
else if (isMATERunning() && UnixCommand::hasTheExecutable(ctn_MATE_TERMINAL)){
s << "--working-directory=" + dirName;
p->startDetached( ctn_MATE_TERMINAL, s );
}
else if (isCinnamonRunning() && UnixCommand::hasTheExecutable(ctn_CINNAMON_TERMINAL)){
s << "--working-directory=" + dirName;
p->startDetached( ctn_CINNAMON_TERMINAL, s );
}
else if (UnixCommand::hasTheExecutable(ctn_XFCE_TERMINAL)){
s << "--working-directory=" + dirName;
p->startDetached( ctn_XFCE_TERMINAL, s );
}
else if (UnixCommand::hasTheExecutable(ctn_LXDE_TERMINAL)){
s << "--working-directory=" + dirName;
p->startDetached( ctn_LXDE_TERMINAL, s );
}
else if (UnixCommand::hasTheExecutable(ctn_XTERM)){
QString cmd = ctn_XTERM +
" -fn \"*-fixed-*-*-*-18-*\" -fg White -bg Black -title xterm -e \"" +
"cd " + dirName + " && /bin/bash\"";
p->startDetached( cmd );
}
}
}
示例2: QLOG_DEBUG
// Index any files that are attached.
void IndexRunner::indexAttachment(qint32 lid, Resource &r) {
if (!officeFound)
return;
QLOG_DEBUG() << "indexing attachment to note " << lid;
if (!keepRunning || pauseIndexing) {
indexTimer->start();
return;
}
ResourceTable rtable(db);
qint32 reslid = rtable.getLid(r.guid);
if (lid <= 0) {
indexTimer->start();
return;
}
QLOG_DEBUG() << "Resource " << reslid;
QString extension = "";
ResourceAttributes attributes;
if (r.attributes.isSet())
attributes = r.attributes;
if (attributes.fileName.isSet()) {
extension = attributes.fileName;
int i = extension.indexOf(".");
if (i != -1)
extension = extension.mid(i);
}
if (extension != ".doc" && extension != ".xls" && extension != ".ppt" &&
extension != ".docx" && extension != ".xlsx" && extension != ".pptx" &&
extension != ".pps" && extension != ".pdf" && extension != ".odt" &&
extension != ".odf" && extension != ".ott" && extension != ".odm" &&
extension != ".html" && extension != ".txt" && extension != ".oth" &&
extension != ".ods" && extension != ".ots" && extension != ".odg" &&
extension != ".otg" && extension != ".odp" && extension != ".otp" &&
extension != ".odb" && extension != ".oxt" && extension != ".htm" &&
extension != ".docm")
return;
QString file = global.fileManager.getDbaDirPath() + QString::number(reslid) +extension;
QFile dataFile(file);
if (!dataFile.exists()) {
QDir dir(global.fileManager.getDbaDirPath());
QStringList filterList;
filterList.append(QString::number(lid)+".*");
QStringList list= dir.entryList(filterList, QDir::Files);
if (list.size() > 0) {
file = global.fileManager.getDbaDirPath()+list[0];
}
}
QString outDir = global.fileManager.getTmpDirPath();
QProcess sofficeProcess;
QString cmd = "soffice --headless --convert-to txt:\"Text\" --outdir "
+outDir + " "
+file;
sofficeProcess.start(cmd,
QIODevice::ReadWrite|QIODevice::Unbuffered);
QLOG_DEBUG() << "Starting soffice ";
sofficeProcess.waitForStarted();
QLOG_DEBUG() << "Waiting for completion";
sofficeProcess.waitForFinished();
int rc = sofficeProcess.exitCode();
QLOG_DEBUG() << "soffice Errors:" << sofficeProcess.readAllStandardError();
QLOG_DEBUG() << "soffice Output:" << sofficeProcess.readAllStandardOutput();
QLOG_DEBUG() << "return code:" << rc;
if (rc == 255) {
QLOG_ERROR() << "soffice not found. Disabling attachment indexing.";
this->officeFound = false;
return;
}
QFile txtFile(outDir+QString::number(reslid) +".txt");
if (txtFile.open(QIODevice::ReadOnly)) {
QString text;
text = txtFile.readAll();
NSqlQuery sql(db);
db->lockForWrite();
sql.prepare("Insert into SearchIndex (lid, weight, source, content) values (:lid, :weight, 'recognition', :content)");
sql.bindValue(":lid", lid);
sql.bindValue(":weight", 100);
sql.bindValue(":content", text);
QLOG_DEBUG() << "Adding note resource to index DB";
sql.exec();
db->unlock();
txtFile.close();
}
QDir dir;
dir.remove(outDir+QString::number(reslid) +".txt");
}
示例3: QStringList
// Function which displays a info box and restarts networking
void Utils::restartNetworking()
{
QMessageBox infoBox;
infoBox.setWindowModality(Qt::ApplicationModal);
infoBox.setWindowTitle(QObject::tr("Restarting network..."));
infoBox.setInformativeText(QObject::tr("Network is restarting, please wait..."));
infoBox.setStandardButtons(QMessageBox::NoButton);
infoBox.show();
QProcess cmd;
cmd.start(QString("/etc/rc.d/netif"), QStringList() << "restart" );
while ( cmd.state() != QProcess::NotRunning ) {
cmd.waitForFinished(100);
QCoreApplication::processEvents();
}
// Set the gateway device name
QString route = getConfFileValue("/etc/rc.conf", "defaultrouter=", 1);
if ( ! route.isEmpty() ) {
infoBox.setInformativeText(QObject::tr("Setting default route..."));
cmd.start(QString("route"), QStringList() << "delete" << "default" );
while ( cmd.state() != QProcess::NotRunning ) {
cmd.waitForFinished(100);
QCoreApplication::processEvents();
}
cmd.start(QString("route"), QStringList() << "add" << "default" << route );
while ( cmd.state() != QProcess::NotRunning ) {
cmd.waitForFinished(100);
QCoreApplication::processEvents();
}
}
// Check for any devices to run DHCP on
QStringList ifs = NetworkInterface::getInterfaces();
for ( QStringList::Iterator it = ifs.begin(); it != ifs.end(); ++it )
{
QString dev = *it;
// Devices we can safely skip
if (dev.indexOf("lo") == 0
|| dev.indexOf("fwe") == 0
|| dev.indexOf("ipfw") == 0
|| dev.indexOf("plip") == 0
|| dev.indexOf("pfsync") == 0
|| dev.indexOf("pflog") == 0
|| dev.indexOf("usbus") == 0
|| dev.indexOf("vboxnet") == 0
|| dev.indexOf("tun") == 0)
continue;
// Check if this device has DHCP enabled
if ( Utils::getConfFileValue( "/etc/rc.conf", "ifconfig_" + dev + "=", 1 ).indexOf("DHCP") != -1 )
{
qDebug() << "Running DHCP on " << dev;
infoBox.setInformativeText(QObject::tr("Running DHCP..."));
cmd.start(QString("/etc/rc.d/dhclient"), QStringList() << "start" << dev );
while ( cmd.state() != QProcess::NotRunning ) {
cmd.waitForFinished(100);
QCoreApplication::processEvents();
}
}
}
infoBox.close();
}
示例4: echoTest_performance
// Reading and writing to a process is not supported on Qt/CE
void tst_QProcess::echoTest_performance()
{
QProcess process;
process.start("testProcessLoopback/testProcessLoopback");
QByteArray array;
array.resize(1024 * 1024);
for (int j = 0; j < array.size(); ++j)
array[j] = 'a' + (j % 20);
QVERIFY(process.waitForStarted());
QTime stopWatch;
stopWatch.start();
qint64 totalBytes = 0;
QByteArray dump;
QSignalSpy readyReadSpy(&process, SIGNAL(readyRead()));
QVERIFY(readyReadSpy.isValid());
while (stopWatch.elapsed() < 2000) {
process.write(array);
while (process.bytesToWrite() > 0) {
int readCount = readyReadSpy.count();
QVERIFY(process.waitForBytesWritten(5000));
if (readyReadSpy.count() == readCount)
QVERIFY(process.waitForReadyRead(5000));
}
while (process.bytesAvailable() < array.size())
QVERIFY2(process.waitForReadyRead(5000), qPrintable(process.errorString()));
dump = process.readAll();
totalBytes += dump.size();
}
qDebug() << "Elapsed time:" << stopWatch.elapsed() << "ms;"
<< "transfer rate:" << totalBytes / (1048.576) / stopWatch.elapsed()
<< "MB/s";
for (int j = 0; j < array.size(); ++j)
QCOMPARE(char(dump.at(j)), char('a' + (j % 20)));
process.closeWriteChannel();
QVERIFY(process.waitForFinished());
}
示例5: lamexp_init_process
bool AnalyzeTask::analyzeAvisynthFile(const QString &filePath, AudioFileModel &info)
{
QProcess process;
lamexp_init_process(process, QFileInfo(m_avs2wavBin).absolutePath());
process.start(m_avs2wavBin, QStringList() << QDir::toNativeSeparators(filePath) << "?");
if(!process.waitForStarted())
{
qWarning("AVS2WAV process failed to create!");
qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
process.kill();
process.waitForFinished(-1);
return false;
}
bool bInfoHeaderFound = false;
while(process.state() != QProcess::NotRunning)
{
if(*m_abortFlag)
{
process.kill();
qWarning("Process was aborted on user request!");
break;
}
if(!process.waitForReadyRead())
{
if(process.state() == QProcess::Running)
{
qWarning("AVS2WAV time out. Killing process and skipping file!");
process.kill();
process.waitForFinished(-1);
return false;
}
}
QByteArray data;
while(process.canReadLine())
{
QString line = QString::fromUtf8(process.readLine().constData()).simplified();
if(!line.isEmpty())
{
int index = line.indexOf(':');
if(index > 0)
{
QString key = line.left(index).trimmed();
QString val = line.mid(index+1).trimmed();
if(bInfoHeaderFound && !key.isEmpty() && !val.isEmpty())
{
if(key.compare("TotalSeconds", Qt::CaseInsensitive) == 0)
{
bool ok = false;
unsigned int duration = val.toUInt(&ok);
if(ok) info.techInfo().setDuration(duration);
}
if(key.compare("SamplesPerSec", Qt::CaseInsensitive) == 0)
{
bool ok = false;
unsigned int samplerate = val.toUInt(&ok);
if(ok) info.techInfo().setAudioSamplerate (samplerate);
}
if(key.compare("Channels", Qt::CaseInsensitive) == 0)
{
bool ok = false;
unsigned int channels = val.toUInt(&ok);
if(ok) info.techInfo().setAudioChannels(channels);
}
if(key.compare("BitsPerSample", Qt::CaseInsensitive) == 0)
{
bool ok = false;
unsigned int bitdepth = val.toUInt(&ok);
if(ok) info.techInfo().setAudioBitdepth(bitdepth);
}
}
}
else
{
if(line.contains("[Audio Info]", Qt::CaseInsensitive))
{
info.techInfo().setAudioType("Avisynth");
info.techInfo().setContainerType("Avisynth");
bInfoHeaderFound = true;
}
}
}
}
}
process.waitForFinished();
if(process.state() != QProcess::NotRunning)
{
process.kill();
process.waitForFinished(-1);
}
//Check exit code
//.........这里部分代码省略.........
示例6: main
//.........这里部分代码省略.........
QString fromDomaine = getenv("DOMAIN");
MailboxList& from = instance.header().from();
for (MailboxList::iterator i = from.begin(); i != from.end(); i++) {
i->mailbox(fromMailbox.toStdString());
i->domain(fromDomaine.toStdString());
}
// Génération du to
Mailbox mailbox;
mailbox.label(libelle.toStdString());
mailbox.mailbox(email.split('@').at(0).toStdString());
mailbox.domain(email.split('@').at(1).toStdString());
MailboxList to;
to.push_back(mailbox);
instance.header().to(to.str());
// substitution des marqueurs
string url = settings.value("modele_url", "http://localhost/%1/%2").toString().arg(id_evenement).arg(id_personne).toStdString();
string affectations = "";
string affectations_html = "";
if (!query_destinataires.value("id_disponibilite").isNull()) { // le destinataire est inscrit à l'évènement et a peut-être des affectations
int id_disponibilite = query_destinataires.value("id_disponibilite").toInt();
query_affectations.addBindValue(id_disponibilite);
if (!query_affectations.exec()) {
qCritical()
<< "Erreur d'execution de la requête de lecture des affectations du destinataire :"
<< query_affectations.lastError();
cout << "4.3.5 System incorrectly configured" << endl;
return EX_CONFIG;
}
if (query_affectations.size() > 0) { // il a des affectations
affectations_html = settings.value("modele_affectations_html_prefixe", "<table><tr><th>De</th><th>à</th><th>Poste</th></tr>").toString().toStdString();
while (query_affectations.next()) {
QString debut = query_affectations.value("debut").toDateTime().toString(); // TODO : formater les dates et les heures
QString fin = query_affectations.value("fin").toDateTime().toString();
QString nom = query_affectations.value("nom").toString();
affectations += settings.value("modele_affectations_texte", "%1 → %2 : %3\n").toString().arg(debut, fin, nom).toStdString();
affectations_html += settings.value("modele_affectations_html", "<tr><td>%1</td><td>%2</td><td>%3</td></tr>").toString().arg(debut, fin, nom).toStdString(); // TODO : htmlentities()
}
affectations_html += settings.value("modele_affectations_html_suffixe", "</table>").toString().toStdString();
}
}
substituer(&instance, url, affectations, affectations_html);
// envoi du message et marquage des destinataires traités
QProcess sendmail;
QStringList arguments;
arguments << "-f" << QString("%[email protected]%2").arg(fromMailbox).arg(fromDomaine);
arguments << email;
stringstream ss; ss << instance;
QString entree = QString::fromStdString(ss.str());
entree.replace(QString("\n.\n"), QString("\n..\n"));
sendmail.start(programme, arguments);
if (sendmail.waitForStarted()) {
sendmail.write(entree.toUtf8());
sendmail.closeWriteChannel();
if (sendmail.waitForFinished() && sendmail.exitStatus() == QProcess::NormalExit && sendmail.exitCode() == EX_OK) {
setLotPersonneTraite.bindValue(":reussi", true);
setLotPersonneTraite.bindValue("erreur", QVariant());
} else {
setLotPersonneTraite.bindValue(":reussi", false);
setLotPersonneTraite.bindValue("erreur", strerror(sendmail.exitCode()));
}
} else {
setLotPersonneTraite.bindValue(":reussi", false);
setLotPersonneTraite.bindValue(":erreur", sendmail.readAllStandardError());
}
setLotPersonneTraite.bindValue(":id_lot", id_lot);
setLotPersonneTraite.bindValue(":id_personne", id_personne);
if(!setLotPersonneTraite.exec()) {
qCritical()
<< "Erreur d'execution de la requête de marquage des envois traités :"
<< setLotPersonneTraite.lastError();
cout << "4.3.5 System incorrectly configured" << endl;
return EX_CONFIG;
}
}
// Marquage du lot traité
QString sender(getenv("SENDER"));
setLotTraite.bindValue(":id_lot", id_lot);
stringstream b;
b << modele;
string modele_lot = b.str();
setLotTraite.bindValue(":modele", modele_lot.c_str());
setLotTraite.bindValue(":expediteur", sender);
if(!setLotTraite.exec()) {
qCritical()
<< "Erreur d'execution de la requête de marquage des envois traités :"
<< setLotTraite.lastError();
cout << "2.1.5 Destination address valid mais le lot n'a pas été marqué 'traité'" << endl;
return EX_OK;
}
// TODO : poster à SENDER la liste des adresses, nom, prenom, ville et identifiant des destinataires en erreur, le nombre d'envois faits (réussis et ratés), un rappel des sujet et date du message original
cout << "2.1.5 Destination address valid" << endl;
return EX_OK;
}
示例7: QString
QString OSInfo::getOSVersion() {
static QString qsCached;
if (! qsCached.isNull())
return qsCached.isEmpty() ? QString() : qsCached;
QString os;
#if defined(Q_OS_WIN)
OSVERSIONINFOEXW ovi;
memset(&ovi, 0, sizeof(ovi));
ovi.dwOSVersionInfoSize=sizeof(ovi);
if (!GetVersionEx(reinterpret_cast<OSVERSIONINFOW *>(&ovi))) {
return QString();
}
os.sprintf("%d.%d.%d.%d", ovi.dwMajorVersion, ovi.dwMinorVersion, ovi.dwBuildNumber, (ovi.wProductType == VER_NT_WORKSTATION) ? 1 : 0);
#elif defined(Q_OS_MAC)
SInt32 major, minor, bugfix;
OSErr err = Gestalt(gestaltSystemVersionMajor, &major);
if (err == noErr)
err = Gestalt(gestaltSystemVersionMinor, &minor);
if (err == noErr)
err = Gestalt(gestaltSystemVersionBugFix, &bugfix);
if (err != noErr)
return QString::number(QSysInfo::MacintoshVersion, 16);
const NXArchInfo *local = NXGetLocalArchInfo();
const NXArchInfo *ai = local ? NXGetArchInfoFromCpuType(local->cputype, CPU_SUBTYPE_MULTIPLE) : NULL;
const char *arch = ai ? ai->name : "unknown";
os.sprintf("%i.%i.%i (%s)", major, minor, bugfix, arch);
#else
#ifdef Q_OS_LINUX
QProcess qp;
QStringList args;
args << QLatin1String("-s");
args << QLatin1String("-d");
qp.start(QLatin1String("lsb_release"), args);
if (qp.waitForFinished(5000)) {
os = QString::fromUtf8(qp.readAll()).simplified();
if (os.startsWith(QLatin1Char('"')) && os.endsWith(QLatin1Char('"')))
os = os.mid(1, os.length() - 2).trimmed();
}
if (os.isEmpty())
qWarning("OSInfo: Failed to execute lsb_release");
qp.terminate();
if (! qp.waitForFinished(1000))
qp.kill();
#endif
if (os.isEmpty()) {
struct utsname un;
if (uname(&un) == 0) {
os.sprintf("%s %s", un.sysname, un.release);
}
}
#endif
if (! os.isNull())
qsCached = os;
else
qsCached = QLatin1String("");
return qsCached;
}
示例8: QLatin1String
void ProcessLauncher::launchProcess()
{
QString commandLine;
if (m_launchOptions.processType == WebProcess) {
commandLine = QLatin1String("%1 \"%2\" %3");
QByteArray webProcessPrefix = qgetenv("QT_WEBKIT2_WP_CMD_PREFIX");
commandLine = commandLine.arg(QLatin1String(webProcessPrefix.constData())).arg(QString(executablePathOfWebProcess()));
#if ENABLE(PLUGIN_PROCESS)
} else if (m_launchOptions.processType == PluginProcess) {
commandLine = QLatin1String("%1 \"%2\" %3 %4");
QByteArray pluginProcessPrefix = qgetenv("QT_WEBKIT2_PP_CMD_PREFIX");
commandLine = commandLine.arg(QLatin1String(pluginProcessPrefix.constData())).arg(QString(executablePathOfPluginProcess()));
#endif
} else
ASSERT_NOT_REACHED();
#if OS(DARWIN)
// Create the listening port.
mach_port_t connector;
mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &connector);
// Insert a send right so we can send to it.
mach_port_insert_right(mach_task_self(), connector, connector, MACH_MSG_TYPE_MAKE_SEND);
// Register port with a service name to the system.
QString serviceName = QStringLiteral("com.nokia.Qt.WebKit.QtWebProcess-%1-%2");
serviceName = serviceName.arg(QString().setNum(getpid()), QString().setNum((size_t)this));
kern_return_t kr = bootstrap_register2(bootstrap_port, const_cast<char*>(serviceName.toUtf8().data()), connector, 0);
ASSERT_UNUSED(kr, kr == KERN_SUCCESS);
commandLine = commandLine.arg(serviceName);
#elif OS(WINDOWS)
CoreIPC::Connection::Identifier connector, clientIdentifier;
if (!CoreIPC::Connection::createServerAndClientIdentifiers(connector, clientIdentifier)) {
// FIXME: What should we do here?
ASSERT_NOT_REACHED();
}
commandLine = commandLine.arg(qulonglong(clientIdentifier));
// Ensure that the child process inherits the client identifier.
::SetHandleInformation(clientIdentifier, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
#else
int sockets[2];
if (socketpair(AF_UNIX, SOCKET_TYPE, 0, sockets) == -1) {
qDebug() << "Creation of socket failed with errno:" << errno;
ASSERT_NOT_REACHED();
return;
}
// Don't expose the ui socket to the web process
while (fcntl(sockets[1], F_SETFD, FD_CLOEXEC) == -1) {
if (errno != EINTR) {
ASSERT_NOT_REACHED();
while (close(sockets[0]) == -1 && errno == EINTR) { }
while (close(sockets[1]) == -1 && errno == EINTR) { }
return;
}
}
int connector = sockets[1];
commandLine = commandLine.arg(sockets[0]);
#endif
#if ENABLE(PLUGIN_PROCESS)
if (m_launchOptions.processType == PluginProcess)
commandLine = commandLine.arg(QString(m_launchOptions.extraInitializationData.get("plugin-path")));
#endif
QProcess* webProcessOrSUIDHelper = new QtWebProcess();
webProcessOrSUIDHelper->setProcessChannelMode(QProcess::ForwardedChannels);
#if ENABLE(SUID_SANDBOX_LINUX)
if (m_launchOptions.processType == WebProcess) {
QString sandboxCommandLine = QLatin1String("\"%1\" \"%2\" %3");
sandboxCommandLine = sandboxCommandLine.arg(QCoreApplication::applicationDirPath() + QLatin1String("/SUIDSandboxHelper"));
sandboxCommandLine = sandboxCommandLine.arg(executablePathOfWebProcess());
sandboxCommandLine = sandboxCommandLine.arg(sockets[0]);
webProcessOrSUIDHelper->start(sandboxCommandLine);
} else
webProcessOrSUIDHelper->start(commandLine);
#else
webProcessOrSUIDHelper->start(commandLine);
#endif
#if OS(UNIX) && !OS(DARWIN)
// Don't expose the web socket to possible future web processes
while (fcntl(sockets[0], F_SETFD, FD_CLOEXEC) == -1) {
if (errno != EINTR) {
ASSERT_NOT_REACHED();
delete webProcessOrSUIDHelper;
return;
}
}
#endif
if (!webProcessOrSUIDHelper->waitForStarted()) {
qDebug() << "Failed to start" << commandLine;
ASSERT_NOT_REACHED();
#if OS(DARWIN)
mach_port_deallocate(mach_task_self(), connector);
//.........这里部分代码省略.........
示例9: switch
bool AC3Encoder::encode(const QString &sourceFile, const AudioFileModel_MetaInfo &metaInfo, const unsigned int duration, const QString &outputFile, volatile bool *abortFlag)
{
QProcess process;
QStringList args;
switch(m_configRCMode)
{
case SettingsModel::VBRMode:
args << "-q" << QString::number(qBound(0, m_configBitrate * 16, 1023));
break;
case SettingsModel::CBRMode:
args << "-b" << QString::number(g_ac3BitratesLUT[qBound(0, m_configBitrate, 18)]);
break;
default:
THROW("Bad rate-control mode!");
break;
}
if(m_configAudioCodingMode >= 1)
{
args << "-acmod" << QString::number(m_configAudioCodingMode - 1);
}
if(m_configDynamicRangeCompression != 5)
{
args << "-dynrng" << QString::number(m_configDynamicRangeCompression);
}
if(m_configExponentSearchSize != 8)
{
args << "-exps" << QString::number(m_configExponentSearchSize);
}
if(m_configFastBitAllocation)
{
args << "-fba" << QString::number(1);
}
if(!m_configCustomParams.isEmpty()) args << m_configCustomParams.split(" ", QString::SkipEmptyParts);
args << QDir::toNativeSeparators(sourceFile);
args << QDir::toNativeSeparators(outputFile);
if(!startProcess(process, m_binary, args))
{
return false;
}
bool bTimeout = false;
bool bAborted = false;
int prevProgress = -1;
QRegExp regExp("progress:(\\s+)(\\d+)%(\\s+)\\|");
while(process.state() != QProcess::NotRunning)
{
if(*abortFlag)
{
process.kill();
bAborted = true;
emit messageLogged("\nABORTED BY USER !!!");
break;
}
process.waitForReadyRead(m_processTimeoutInterval);
if(!process.bytesAvailable() && process.state() == QProcess::Running)
{
process.kill();
qWarning("Aften process timed out <-- killing!");
emit messageLogged("\nPROCESS TIMEOUT !!!");
bTimeout = true;
break;
}
while(process.bytesAvailable() > 0)
{
QByteArray line = process.readLine();
QString text = QString::fromUtf8(line.constData()).simplified();
if(regExp.lastIndexIn(text) >= 0)
{
bool ok = false;
int progress = regExp.cap(2).toInt(&ok);
if(ok && (progress > prevProgress))
{
emit statusUpdated(progress);
prevProgress = qMin(progress + 2, 99);
}
}
else if(!text.isEmpty())
{
emit messageLogged(text);
}
}
}
process.waitForFinished();
if(process.state() != QProcess::NotRunning)
{
process.kill();
process.waitForFinished(-1);
}
emit statusUpdated(100);
emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));
//.........这里部分代码省略.........
示例10: zip
bool zip()
{
//! [0]
QProcess gzip;
gzip.start("gzip", QStringList() << "-c");
if (!gzip.waitForStarted())
return false;
gzip.write("Qt rocks!");
gzip.closeWriteChannel();
if (!gzip.waitForFinished())
return false;
QByteArray result = gzip.readAll();
//! [0]
gzip.start("gzip", QStringList() << "-d" << "-c");
gzip.write(result);
gzip.closeWriteChannel();
if (!gzip.waitForFinished())
return false;
qDebug("Result: %s", gzip.readAll().data());
return true;
}
示例11: QString
void FeedbackDialog::GenerateSpecs()
{
// Gather some information about the system and embed it into the report
QDesktopWidget* screen = QApplication::desktop();
QString os_version = "Operating system: ";
QString qt_version = QString("Qt version: ") + QT_VERSION_STR + QString("\n");
QString total_ram = "Total RAM: ";
QString number_of_cores = "Number of cores: ";
QString compiler_bits = "Compiler architecture: ";
QString compiler_version = "Compiler version: ";
QString kernel_line = "Kernel: ";
QString screen_size = "Size of the screen(s): " +
QString::number(screen->width()) + "x" + QString::number(screen->height()) + "\n";
QString number_of_screens = "Number of screens: " + QString::number(screen->screenCount()) + "\n";
QString processor_name = "Processor: ";
// platform specific code
#ifdef Q_OS_MACX
number_of_cores += QString::number(sysconf(_SC_NPROCESSORS_ONLN)) + "\n";
uint64_t memsize;
size_t len = sizeof(memsize);
static int mib_s[2] = { CTL_HW, HW_MEMSIZE };
if (sysctl (mib_s, 2, &memsize, &len, NULL, 0) == 0)
total_ram += QString::number(memsize/1024/1024) + " MB\n";
else
total_ram += "Error getting total RAM information\n";
int mib[] = {CTL_KERN, KERN_OSRELEASE};
sysctl(mib, sizeof mib / sizeof(int), NULL, &len, NULL, 0);
char *kernelVersion = (char *)malloc(sizeof(char)*len);
sysctl(mib, sizeof mib / sizeof(int), kernelVersion, &len, NULL, 0);
QString kernelVersionStr = QString(kernelVersion);
free(kernelVersion);
int major_version = kernelVersionStr.split(".").first().toUInt() - 4;
int minor_version = kernelVersionStr.split(".").at(1).toUInt();
os_version += QString("Mac OS X 10.%1.%2").arg(major_version).arg(minor_version) + " ";
switch(major_version)
{
case 4: os_version += "\"Tiger\"\n"; break;
case 5: os_version += "\"Leopard\"\n"; break;
case 6: os_version += "\"Snow Leopard\"\n"; break;
case 7: os_version += "\"Lion\"\n"; break;
case 8: os_version += "\"Mountain Lion\"\n"; break;
default: os_version += "\"Unknown version\"\n"; break;
}
#endif
#ifdef Q_OS_WIN
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
number_of_cores += QString::number(sysinfo.dwNumberOfProcessors) + "\n";
MEMORYSTATUSEX status;
status.dwLength = sizeof(status);
GlobalMemoryStatusEx(&status);
total_ram += QString::number(status.ullTotalPhys/1024/1024) + " MB\n";
switch(QSysInfo::windowsVersion())
{
case QSysInfo::WV_NT: os_version += "Windows NT\n"; break;
case QSysInfo::WV_2000: os_version += "Windows 2000\n"; break;
case QSysInfo::WV_XP: os_version += "Windows XP\n"; break;
case QSysInfo::WV_2003: os_version += "Windows Server 2003\n"; break;
case QSysInfo::WV_VISTA: os_version += "Windows Vista\n"; break;
case QSysInfo::WV_WINDOWS7: os_version += "Windows 7\n"; break;
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
case QSysInfo::WV_WINDOWS8: os_version += "Windows 8\n"; break;
#endif
default: os_version += "Windows (Unknown version)\n"; break;
}
kernel_line += "Windows kernel\n";
#endif
#ifdef Q_OS_LINUX
number_of_cores += QString::number(sysconf(_SC_NPROCESSORS_ONLN)) + "\n";
quint32 pages = sysconf(_SC_PHYS_PAGES);
quint32 page_size = sysconf(_SC_PAGE_SIZE);
quint32 total = pages * page_size / 1024 / 1024;
total_ram += QString::number(total) + " MB\n";
os_version += "GNU/Linux or BSD\n";
#endif
// uname -a
#if defined(Q_OS_LINUX) || defined(Q_OS_MAC)
QProcess *process = new QProcess();
QStringList arguments = QStringList("-a");
process->start("uname", arguments);
if (process->waitForFinished())
kernel_line += QString(process->readAll());
delete process;
#endif
#if (!defined(Q_OS_MAC) && defined(__i386__)) || defined(__x86_64__)
// cpu info
quint32 registers[4];
quint32 i;
i = 0x80000002;
asm volatile
//.........这里部分代码省略.........
示例12: qDebug
/** Runs the specified command (should be ffmpeg), and lets
* writeFrame pipe data into it 1 frame at a time.
*
* @param[in] strCmd A string containing the command to execute and
* all of its arguments
* @param[out] progress A function that takes one float argument
* (the percentage of the ffmpeg operation complete) and
* may display the output to the user in any way it
* sees fit.
* @param[in] writeFrame A function that takes two arguments, a
* process (the ffmpeg process) and an integer
* (frames processed or -1, see full description).
* This function should write a single frame to the
* process. The function returns true value if it
* actually wrote a frame.
*
* This function operates generally as follows:
* 1. Spawn process with the command from strCmd
* 2. Check ffmpeg's output for a progress update.
* 3. Add frames with writeFrame until it returns false.
* 4. Repeat from step 2 until all frames have been written.
*
* The idea is that there are two forms of processing occuring
* simultaneously, generating frames to send to ffmpeg, and ffmpeg
* encoding those frames. Whether these this actually occur
* concurrently or one after another appears to depend on the environment.
*
* The writeFrame function deserves a bit of extra details. It does
* not only return false when there is an error in generating or
* writing a frame, it also does it when it wants to "return control"
* to the rest of the executeFFMpegPipe function for the purposes of
* reading updates from ffmpeg's output. This should be done every
* once in a while if possible, but with some formats (specifically gif),
* all frames must be loaded before any processing can continue, so
* there is no point returning false for it until all frames have
* been written. writeFrame is also responsible for closing the writeChannel
* of the process when it has finished writing all frames. This indicates
* to executeFFMpegPipe that it no longer needs to call writeFrame.
*
* @return Returns Status::OK if everything went well, and Status::FAIL
* and error is detected (usually a non-zero exit code for ffmpeg).
*/
Status MovieExporter::executeFFMpegPipe(QString strCmd, std::function<void(float)> progress, std::function<bool(QProcess&, int)> writeFrame)
{
qDebug() << strCmd;
QProcess ffmpeg;
ffmpeg.setReadChannel(QProcess::StandardOutput);
// FFmpeg writes to stderr only for some reason, so we just read both channels together
ffmpeg.setProcessChannelMode(QProcess::MergedChannels);
ffmpeg.start(strCmd);
if (ffmpeg.waitForStarted())
{
int framesGenerated = 0;
int lastFrameProcessed = 0;
const int frameStart = mDesc.startFrame;
const int frameEnd = mDesc.endFrame;
while(ffmpeg.state() == QProcess::Running)
{
if (mCanceled)
{
ffmpeg.terminate();
return Status::CANCELED;
}
// Check FFmpeg progress
int framesProcessed = -1;
if(ffmpeg.waitForReadyRead(10))
{
QString output(ffmpeg.readAll());
QStringList sList = output.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);
for (const QString& s : sList)
{
qDebug() << "[ffmpeg]" << s;
}
if(output.startsWith("frame="))
{
lastFrameProcessed = framesProcessed = output.mid(6, output.indexOf(' ')).toInt();
}
}
if(!ffmpeg.isWritable())
{
continue;
}
while(writeFrame(ffmpeg, framesProcessed))
{
framesGenerated++;
const float percentGenerated = framesGenerated / static_cast<float>(frameEnd - frameStart);
const float percentConverted = lastFrameProcessed / static_cast<float>(frameEnd - frameStart);
progress((percentGenerated + percentConverted) / 2);
}
const float percentGenerated = framesGenerated / static_cast<float>(frameEnd - frameStart);
const float percentConverted = lastFrameProcessed / static_cast<float>(frameEnd - frameStart);
progress((percentGenerated + percentConverted) / 2);
}
//.........这里部分代码省略.........
示例13: QProcess
void MainWindow::slot_pushButton_tb_info_clicked() {
// ui->pushButton_tb_info->setEnabled(false);
QProcess* process = new QProcess();
process->startDetached("./app/BondInfo", QStringList()<<"000");
}
示例14: QProcess
Device::Device()
{
#ifdef i386
m_model = EMULATOR;
return;
#endif
QStringList list;
QProcess *myProcess = new QProcess();
list << "-c" << "grep erial /proc/cpuinfo|cut -c12-15";
myProcess->start("/bin/sh", list);
if (myProcess->waitForReadyRead(10000)) {
QByteArray array = myProcess->readAll();
array.truncate(array.indexOf("\n"));
bool ok;
int sn = QString(array).toInt(&ok, 16);
if (ok) {
qDebug("serial: %X", sn);
} else {
qDebug("unexpected output");
return;
}
switch(sn) {
case 0xB002:
case 0xB003:
m_model = K2; // may not work as K2 doesn't print SN in cpuinfo
break;
case 0xB004:
case 0xB005:
case 0xB009:
m_model = KDX;
break;
case 0xB006:
case 0xB008:
case 0xB00A:
m_model = K3;
break;
case 0xB00E:
m_model = K4NT;
break;
case 0xB00F:
case 0xB010:
case 0xB011:
case 0xB012: // ???
m_model = KT;
break;
case 0x9023:
case 0xB023:
m_model = K4NTB;
break;
case 0xB01B:
case 0xB01C:
case 0xB01D:
case 0xB01F:
case 0xB024:
m_model = KPW;
break;
default:
qDebug("Unknown model: %X", sn);
}
}
myProcess->close();
}
示例15: getFileContents
bool InitDriveThread::method_resizePartitions()
{
int newStartOfRescuePartition = getFileContents(sysclassblock(_drive, 1)+"/start").trimmed().toInt();
int 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;
}
//.........这里部分代码省略.........