bool resource_minitor::get_net_usage__() { QProcess process; process.start("cat /proc/net/dev"); //读取文件/proc/net/dev获取网络收发包数量,再除取样时间得到网络速度 process.waitForFinished(); process.readLine(); process.readLine(); while(!process.atEnd()) { QString str = process.readLine(); str.replace("\n",""); str.replace(QRegExp("( ){1,}")," "); auto lst = str.split(" "); if(lst.size() > 9 && lst[0] == "enp2s0:") { double recv = 0; double send = 0; if(lst.size() > 1) recv = lst[1].toDouble(); if(lst.size() > 9) send = lst[9].toDouble(); qDebug("%s 接收速度:%.0lfbyte/s 发送速度:%.0lfbyte/s",lst[0].toStdString().c_str(),(recv - m_recv_bytes__) / (m_timer_interval__ / 1000.0),(send - m_send_bytes__) / (m_timer_interval__ / 1000.0)); m_recv_bytes__ = recv; m_send_bytes__ = send; } } return true; }
void MemSpecParser::parseHelperProg(MemSpecs* specs) { QProcess proc; proc.setWorkingDirectory(_buildDir); // Invoke the command QString cmd = "./memspec"; proc.start(cmd); proc.waitForFinished(-1); if (proc.exitStatus() || proc.exitCode() != 0) { _errorOutput = proc.readAllStandardError(); memSpecParserError( QString("Command failed with exit code %2 and exit status \"%3\": %1") .arg(cmd) .arg(proc.exitCode()) .arg((proc.exitStatus()) ? "crashed" : "normal")); } const int bufsize = 1024; char buf[1024]; QRegExp re("^\\s*([^\\s]+)\\s*=\\s*(.*)$"); while (!proc.atEnd() && proc.readLine(buf, bufsize) > 0) { if (re.exactMatch(buf)) // Update the given MemSpecs object with the parsed key-value pair specs->setFromKeyValue(re.cap(1), re.cap(2).trimmed()); } }
bool QProcessProto::atEnd() const { QProcess *item = qscriptvalue_cast<QProcess*>(thisObject()); if (item) return item->atEnd(); return false; }
void imageio::init() { if(isInitialized)return; QProcess im; im.start("identify", QStringList() << "-list" << "format"); im.waitForFinished(); formats.clear(); while(!im.atEnd()) { QString line = im.readLine().trimmed(); // 3FR r-- Hasselblad CFV/H3D39II line.replace(" "," "); line.replace(" " ," "); //3FR r-- Hasselblad CFV/H3D39II QString word1 = line.mid(0, line.indexOf(" ")); QString word2 = line.mid(word1.length()+1, 3); QString desc = line.mid(word1.length()+word2.length()+2); bool nbs = word1.contains("*"); word1.replace("*",""); // At this stage we can check is this a valid file format description. // Word2 must only be in form of [r-][w-][+-]. bool valid = true, write, read, multi; if(word2[0]=='r')read=true; else if(word2[0]=='-')read=false; else valid=false; if(word2[1]=='w')write=true; else if(word2[0]=='-')write=false; else valid=false; if(word2[2]=='+')multi=true; else if(word2[2]=='-')multi=false; else valid=false; if(valid) { imageFormat* f = new imageFormat; f->description = desc; f->format = word1; f->read = read; f->write = write; f->multi = multi; f->nativeblob = nbs; if(desc.toLower().contains("video")) f->warnForHugeData = true; //Settings: if(f->format=="PDF")f->additionalArgs << "-density" << "1000"; //Exclusions: TXT files won't be added to the list at all! if(f->format!="TXT") formats << f; QString fDesc = f->format.rightJustified(10,' ',true)+ " "+(f->read?"R":"-") + (f->write?"W":"-") + (f->multi?" M":" -") +" "+f->description; qDebug(fDesc.toLocal8Bit()); } } isInitialized = true; }
QStringList DeviceEnumerator_unix::getUserFriendlyNames(const QStringList &devices) const { QStringList returnList; foreach (QString s, devices) { #ifdef Q_OS_LINUX qint64 size = driveSize(s); QStringList partInfo = getPartitionsInfo(s); QTextStream friendlyName(&s); friendlyName.setRealNumberNotation(QTextStream::FixedNotation); friendlyName.setRealNumberPrecision(2); friendlyName << " ("; if (size > 0) { friendlyName << size/(1024*1024*1024.0) << " GB"; } else { friendlyName << "??? GB"; } friendlyName << ", partitions: "; foreach (QString partition, partInfo) { friendlyName << partition << ", "; } s.chop(2); friendlyName << ")"; returnList.append(s); #else QProcess lsblk; lsblk.start(QString("diskutil info %1").arg(s), QIODevice::ReadOnly); lsblk.waitForStarted(); lsblk.waitForFinished(); QString output = lsblk.readLine(); QStringList iddata; QString item = ""; while (!lsblk.atEnd()) { output = output.trimmed(); // Odd trailing whitespace if (output.contains("Device / Media Name:")) { // We want the volume name of this device output.replace("Device / Media Name: ",""); iddata.append(output); }else if (output.contains("Device Identifier:")) { // We want the volume name of this device output.replace("Device Identifier: ",""); iddata.append(output); }else if (output.contains("Total Size:")) { // We want the volume name of this device output.replace("Total Size: ",""); QStringList tokens = output.split(" "); iddata.append( "("+tokens[0]+tokens[1]+")"); } output = lsblk.readLine(); } foreach(QString each,iddata) { item += each+": "; }
std::list<int> ProcessControl::getPidProcessByName(std::string name) { std::list<int> result; qDebug() << "ProcessControl::getPidProcessByName: Begin:"; #ifndef WIN32 QProcess myprocess; std::string command = std::string("ps -C ")+name+std::string(" -o pid --no-heading"); qDebug() << "ProcessControl::getPidProcessByName: comando solicitado:" << command.c_str(); myprocess.start(command.c_str()); if (!myprocess.waitForFinished()) return result; while (!myprocess.atEnd()) { char buf[16]; qint64 length = myprocess.readLine(buf,sizeof(buf)); if (length != -1) { QString mystring(buf); result.push_back(mystring.toInt()); } else break; } #else DWORD aProcesses[1024], cbNeeded, cProcesses; if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ) return result; // Calculate how many process identifiers were returned. cProcesses = cbNeeded / sizeof(DWORD); for ( int i = 0 ; i < cProcesses; i++) { if (aProcesses[i] != 0) { std::wstring nombre = PrintProcessNameAndID( aProcesses[i] ); std::string temp; std::copy(nombre.begin(), nombre.end(), std::back_inserter(temp)); qDebug() << "ProcessControl::getPidProcessByName: New pid name" << aProcesses[i] << temp.c_str(); if (QString(temp.c_str()).toLower()==QString(name.c_str()).toLower()) { qDebug() << "ProcessControl::getPidProcessByName: found proccess"; result.push_back((int)aProcesses[i]); } } } #endif return result; }
bool BlockingIODevice::atEnd() const { /* * XXX: QProcess::atEnd() documentation is wrong -- it will return true * even when the process is running --, so we try to workaround that here. */ if (m_device->atEnd()) { if (m_device->state() == QProcess::Running) { if (!m_device->waitForReadyRead(-1)) { return true; } } } return false; }
bool KBugReport::sendBugReport() { #ifndef EMSCRIPTEN QString recipient ( d->m_aboutData ? d->m_aboutData->bugAddress() : QString::fromLatin1("*****@*****.**") ); QString command; command = KStandardDirs::locate("exe", "ksendbugmail"); if (command.isEmpty()) command = KStandardDirs::findExe( QString::fromLatin1("ksendbugmail") ); QProcess proc; QStringList args; args << "--subject" << d->m_subject->text() << "--recipient" << recipient; proc.start( command, args ); //kDebug() << command << args; if (!proc.waitForStarted()) { kError() << "Unable to open a pipe to " << command << endl; return false; } proc.write( text().toUtf8() ); proc.closeWriteChannel(); proc.waitForFinished(); kDebug() << "kbugreport: sendbugmail exit, status " << proc.exitStatus() << " code " << proc.exitCode(); QByteArray line; if (proc.exitStatus() == QProcess::NormalExit && proc.exitCode() != 0) { // XXX not stderr? while (!proc.atEnd()) line = proc.readLine(); d->lastError = QString::fromUtf8( line ); return false; } return true; #else kWarning() << "Bug report stuff not supported on Emscripten"; return false; #endif }
QStringList DeviceEnumerator_unix::getRemovableDeviceNames() const { QStringList names; QStringList unmounted; #ifdef Q_OS_LINUX names = getDeviceNamesFromSysfs(); foreach (QString device, names) { if (! checkIsMounted(device)) unmounted << "/dev/"+device; } return unmounted; #else QProcess lsblk; lsblk.start("diskutil list", QIODevice::ReadOnly); lsblk.waitForStarted(); lsblk.waitForFinished(); QString device = lsblk.readLine(); while (!lsblk.atEnd()) { device = device.trimmed(); // Odd trailing whitespace if (device.startsWith("/dev/disk")) { QString name = device.split(QRegExp("\\s+")).first(); #if USE_ONLY_USB_DEVICES_ON_OSX == 0 names << name; #else // We only want to add USB devics if (this->checkIfUSB(name)) { names << name; } #endif } device = lsblk.readLine(); } return names; #endif }
bool resource_minitor::get_disk_space__() { QProcess process; process.start("df -k"); process.waitForFinished(); process.readLine(); while(!process.atEnd()) { QString str = process.readLine(); if(str.startsWith("/dev/sda")) { str.replace("\n",""); str.replace(QRegExp("( ){1,}")," "); auto lst = str.split(" "); if(lst.size() > 5) qDebug("挂载点:%s 已用:%.0lfMB 可用:%.0lfMB",lst[5].toStdString().c_str(),lst[2].toDouble()/1024.0,lst[3].toDouble()/1024.0); } } return true; }
void SofaModeler::sofaExited(int exitCode, QProcess::ExitStatus existStatus) { QProcess *p = ((QProcess*) sender()); std::string programName; programName = p->objectName().toStdString(); removeTemporaryFiles(programName); if (existStatus == QProcess::NormalExit ) { p->closeWriteChannel(); disconnect(p, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(sofaExited(int, QProcess::ExitStatus))); disconnect(p, SIGNAL( readyReadStandardOutput () ), this , SLOT ( redirectStdout() ) ); disconnect(p, SIGNAL( readyReadStandardError () ), this , SLOT ( redirectStderr() ) ); if(p->atEnd()) std::cout << "Sofa exited safely." << std::endl; else std::cout << "Chelou." << std::endl; p->kill(); return; }
void KeyboardLayoutConfig::loadSettings() { // load current settings from the output of setxkbmap command QProcess setxkbmap; setxkbmap.start(QLatin1String("setxkbmap -query -verbose 5")); setxkbmap.waitForFinished(); if(setxkbmap.exitStatus() == QProcess::NormalExit) { QList<QByteArray> layouts, variants; while(!setxkbmap.atEnd()) { QByteArray line = setxkbmap.readLine(); if(line.startsWith("model:")) { keyboardModel_ = QString::fromLatin1(line.mid(6).trimmed()); } else if(line.startsWith("layout:")) { layouts = line.mid(7).trimmed().split(','); } else if(line.startsWith("variant:")) { variants = line.mid(8).trimmed().split(','); } else if(line.startsWith("options:")) { const QList<QByteArray> options = line.mid(9).trimmed().split(','); Q_FOREACH(const QByteArray &option, options) { if(option.startsWith("grp:")) switchKey_ = QString::fromLatin1(option); else currentOptions_ << QString::fromLatin1(option); } } } const int size = layouts.size(), variantsSize = variants.size(); for(int i = 0; i < size; ++i) { currentLayouts_.append(QPair<QString, QString>(layouts.at(i), variantsSize > 0 ? variants.at(i) : QString())); } setxkbmap.close(); }
void RCSTest::verifyRevisions() { RCS::init(); RCS *rcs = new RCS(test_file); QList<Revision> rcsrevs; for (QList<Revision>::iterator i=rcs->begin(); i!=rcs->end(); ++i) { Revision rev = *i; QStringList log = rev.log.split("\n"); log.removeFirst(); rev.log = log.join("\n"); rcsrevs.append(rev); } QProcess rlog; rlog.start("rlog", QStringList() << test_file); rlog.waitForFinished(); QList<Revision> realrevs; QRegExp revlock("revision\\s+([\\.\\d]+)(\\s+locked by: (\\w+);)?\\n"); revlock.setPatternSyntax(QRegExp::RegExp2); QRegExp dateauth("date: (\\d\\d\\d\\d/\\d\\d/\\d\\d \\d\\d\\:\\d\\d\\:\\d\\d);\\s+author\\: (\\w+);\\s+state\\: (\\w+);(\\s+lines: \\+(\\d+) \\-(\\d+))?\\n"); QMap <QString, Revision> realrevsmap; QString line; while (!rlog.atEnd() && line != "----------------------------\n") // skip header line = rlog.readLine(); while (!rlog.atEnd()) { QStringList lines; while (!rlog.atEnd()) { line = rlog.readLine(); if (line != "----------------------------\n" && line != "=============================================================================\n") lines.append(line); else break; } QStringList comment; for (int i = 2; i< lines.size(); i++) comment.append(lines.at(i)); Revision rev; rev.log = comment.join(""); revlock.indexIn(lines[0]); rev.locked_by = revlock.capturedTexts()[3]; rev.rev = revlock.capturedTexts()[1]; dateauth.indexIn(lines[1]); rev.date = dateauth.capturedTexts()[1].replace("/", "-"); rev.author = dateauth.capturedTexts()[2]; rev.filename = test_file; realrevs.insert(0, rev); realrevsmap[rev.rev] = rev; } CPPUNIT_ASSERT(realrevs.size() == rcsrevs.size()); for (int i = 0; i < realrevs.size(); i++) { Revision rcsr = rcsrevs.at(i); Revision realr = realrevsmap[rcsr.rev]; /* qDebug() << realr.author << rcsr.author; qDebug() << realr.date << rcsr.date; qDebug() << realr.filename << rcsr.filename; qDebug() << realr.locked_by << rcsr.locked_by; qDebug() << realr.log << rcsr.log; qDebug() << realr.rev << rcsr.rev; qDebug() << "----------"; qDebug() << (realr == rcsr); */ CPPUNIT_ASSERT (realr == rcsr); } }
/** * Starting point for the retracing thread. * * Overrides QThread::run(). */ void Retracer::run() { QString msg = QLatin1String("Replay finished!"); /* * Construct command line */ QString prog; QStringList arguments; switch (m_api) { case trace::API_GL: prog = QLatin1String("glretrace"); break; case trace::API_EGL: prog = QLatin1String("eglretrace"); break; case trace::API_DX: case trace::API_D3D7: case trace::API_D3D8: case trace::API_D3D9: case trace::API_DXGI: #ifdef Q_OS_WIN prog = QLatin1String("d3dretrace"); #else prog = QLatin1String("wine"); arguments << QLatin1String("d3dretrace.exe"); #endif break; default: emit finished(QLatin1String("Unsupported API")); return; } if (m_singlethread) { arguments << QLatin1String("--singlethread"); } if (m_captureState) { arguments << QLatin1String("-D"); arguments << QString::number(m_captureCall); } else if (m_captureThumbnails) { arguments << QLatin1String("-s"); // emit snapshots arguments << QLatin1String("-"); // emit to stdout } else if (isProfiling()) { if (m_profileGpu) { arguments << QLatin1String("--pgpu"); } if (m_profileCpu) { arguments << QLatin1String("--pcpu"); } if (m_profilePixels) { arguments << QLatin1String("--ppd"); } } else { if (m_doubleBuffered) { arguments << QLatin1String("--db"); } else { arguments << QLatin1String("--sb"); } if (m_benchmarking) { arguments << QLatin1String("-b"); } } arguments << m_fileName; /* * Support remote execution on a separate target. */ if (m_remoteTarget.length() != 0) { arguments.prepend(prog); arguments.prepend(m_remoteTarget); prog = QLatin1String("ssh"); } /* * Start the process. */ QProcess process; process.start(prog, arguments, QIODevice::ReadOnly); if (!process.waitForStarted(-1)) { emit finished(QLatin1String("Could not start process")); return; } /* * Process standard output */ QList<QImage> thumbnails; QVariantMap parsedJson; trace::Profile* profile = NULL; process.setReadChannel(QProcess::StandardOutput); if (process.waitForReadyRead(-1)) { BlockingIODevice io(&process); if (m_captureState) { /* * Parse JSON from the output. * * XXX: QJSON's scanner is inneficient as it abuses single * character QIODevice::peek (not cheap), instead of maintaining a * lookahead character on its own. */ bool ok = false; QJson::Parser jsonParser; // Allow Nan/Infinity jsonParser.allowSpecialNumbers(true); #if 0 parsedJson = jsonParser.parse(&io, &ok).toMap(); #else /* * XXX: QJSON expects blocking IO, and it looks like * BlockingIODevice does not work reliably in all cases. */ process.waitForFinished(-1); parsedJson = jsonParser.parse(&process, &ok).toMap(); #endif if (!ok) { msg = QLatin1String("failed to parse JSON"); } } else if (m_captureThumbnails) { /* * Parse concatenated PNM images from output. */ while (!io.atEnd()) { unsigned channels = 0; unsigned width = 0; unsigned height = 0; char header[512]; qint64 headerSize = 0; int headerLines = 3; // assume no optional comment line for (int headerLine = 0; headerLine < headerLines; ++headerLine) { qint64 headerRead = io.readLine(&header[headerSize], sizeof(header) - headerSize); // if header actually contains optional comment line, ... if (headerLine == 1 && header[headerSize] == '#') { ++headerLines; } headerSize += headerRead; } const char *headerEnd = image::readPNMHeader(header, headerSize, &channels, &width, &height); // if invalid PNM header was encountered, ... if (header == headerEnd) { qDebug() << "error: invalid snapshot stream encountered"; break; } // qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height"; QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888); int rowBytes = channels * width; for (int y = 0; y < height; ++y) { unsigned char *scanLine = snapshot.scanLine(y); qint64 readBytes = io.read((char *) scanLine, rowBytes); Q_ASSERT(readBytes == rowBytes); (void)readBytes; } QImage thumb = thumbnail(snapshot); thumbnails.append(thumb); } Q_ASSERT(process.state() != QProcess::Running); } else if (isProfiling()) { profile = new trace::Profile(); while (!io.atEnd()) { char line[256]; qint64 lineLength; lineLength = io.readLine(line, 256); if (lineLength == -1) break; trace::Profiler::parseLine(line, profile); } } else { QByteArray output; output = process.readAllStandardOutput(); if (output.length() < 80) { msg = QString::fromUtf8(output); } } } /* * Wait for process termination */ process.waitForFinished(-1); if (process.exitStatus() != QProcess::NormalExit) { msg = QLatin1String("Process crashed"); } else if (process.exitCode() != 0) { msg = QLatin1String("Process exited with non zero exit code"); } /* * Parse errors. */ QList<ApiTraceError> errors; process.setReadChannel(QProcess::StandardError); QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$"); while (!process.atEnd()) { QString line = process.readLine(); if (regexp.indexIn(line) != -1) { ApiTraceError error; error.callIndex = regexp.cap(1).toInt(); error.type = regexp.cap(2); error.message = regexp.cap(3); errors.append(error); } else if (!errors.isEmpty()) { // Probably a multiligne message ApiTraceError &previous = errors.last(); if (line.endsWith("\n")) { line.chop(1); } previous.message.append('\n'); previous.message.append(line); } } /* * Emit signals */ if (m_captureState) { ApiTraceState *state = new ApiTraceState(parsedJson); emit foundState(state); } if (m_captureThumbnails && !thumbnails.isEmpty()) { emit foundThumbnails(thumbnails); } if (isProfiling() && profile) { emit foundProfile(profile); } if (!errors.isEmpty()) { emit retraceErrors(errors); } emit finished(msg); }
/** * Starting point for the retracing thread. * * Overrides QThread::run(). */ void Retracer::run() { QString msg = QLatin1String("Replay finished!"); /* * Construct command line */ QString prog; QStringList arguments; switch (m_api) { case trace::API_GL: prog = QLatin1String("glretrace"); break; case trace::API_EGL: prog = QLatin1String("eglretrace"); break; case trace::API_DX: case trace::API_D3D7: case trace::API_D3D8: case trace::API_D3D9: case trace::API_DXGI: #ifdef Q_OS_WIN prog = QLatin1String("d3dretrace"); #else prog = QLatin1String("wine"); arguments << QLatin1String("d3dretrace.exe"); #endif break; default: emit finished(QLatin1String("Unsupported API")); return; } arguments << retraceArguments() << m_fileName; /* * Support remote execution on a separate target. */ if (m_remoteTarget.length() != 0) { arguments.prepend(prog); arguments.prepend(m_remoteTarget); prog = QLatin1String("ssh"); } /* * Start the process. */ { QDebug debug(QtDebugMsg); debug << "Running:"; debug << prog; foreach (const QString &argument, arguments) { debug << argument; } } QProcess process; process.start(prog, arguments, QIODevice::ReadOnly); if (!process.waitForStarted(-1)) { emit finished(QLatin1String("Could not start process")); return; } /* * Process standard output */ ImageHash thumbnails; QVariantMap parsedJson; trace::Profile* profile = NULL; process.setReadChannel(QProcess::StandardOutput); if (process.waitForReadyRead(-1)) { BlockingIODevice io(&process); if (m_captureState) { parsedJson = decodeUBJSONObject(&io).toMap(); process.waitForFinished(-1); } else if (m_captureThumbnails) { /* * Parse concatenated PNM images from output. */ while (!io.atEnd()) { image::PNMInfo info; char header[512]; qint64 headerSize = 0; int headerLines = 3; // assume no optional comment line for (int headerLine = 0; headerLine < headerLines; ++headerLine) { qint64 headerRead = io.readLine(&header[headerSize], sizeof(header) - headerSize); // if header actually contains optional comment line, ... if (headerLine == 1 && header[headerSize] == '#') { ++headerLines; } headerSize += headerRead; } const char *headerEnd = image::readPNMHeader(header, headerSize, info); // if invalid PNM header was encountered, ... if (headerEnd == NULL || info.channelType != image::TYPE_UNORM8) { qDebug() << "error: invalid snapshot stream encountered"; break; } unsigned channels = info.channels; unsigned width = info.width; unsigned height = info.height; // qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height"; QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888); int rowBytes = channels * width; for (int y = 0; y < height; ++y) { unsigned char *scanLine = snapshot.scanLine(y); qint64 readBytes = io.read((char *) scanLine, rowBytes); Q_ASSERT(readBytes == rowBytes); (void)readBytes; } QImage thumb = thumbnail(snapshot); thumbnails.insert(info.commentNumber, thumb); } Q_ASSERT(process.state() != QProcess::Running); } else if (isProfiling()) { profile = new trace::Profile(); while (!io.atEnd()) { char line[256]; qint64 lineLength; lineLength = io.readLine(line, 256); if (lineLength == -1) break; trace::Profiler::parseLine(line, profile); } } else { QByteArray output; output = process.readAllStandardOutput(); if (output.length() < 80) { msg = QString::fromUtf8(output); } } } /* * Wait for process termination */ process.waitForFinished(-1); if (process.exitStatus() != QProcess::NormalExit) { msg = QLatin1String("Process crashed"); } else if (process.exitCode() != 0) { msg = QLatin1String("Process exited with non zero exit code"); } /* * Parse errors. */ QList<ApiTraceError> errors; process.setReadChannel(QProcess::StandardError); QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$"); while (!process.atEnd()) { QString line = process.readLine(); if (regexp.indexIn(line) != -1) { ApiTraceError error; error.callIndex = regexp.cap(1).toInt(); error.type = regexp.cap(2); error.message = regexp.cap(3); errors.append(error); } else if (!errors.isEmpty()) { // Probably a multiligne message ApiTraceError &previous = errors.last(); if (line.endsWith("\n")) { line.chop(1); } previous.message.append('\n'); previous.message.append(line); } } /* * Emit signals */ if (m_captureState) { ApiTraceState *state = new ApiTraceState(parsedJson); emit foundState(state); } if (m_captureThumbnails && !thumbnails.isEmpty()) { emit foundThumbnails(thumbnails); } if (isProfiling() && profile) { emit foundProfile(profile); } if (!errors.isEmpty()) { emit retraceErrors(errors); } emit finished(msg); }
// -------------------------------------------------------------------------- // // Function // Name: unsigned int ProcessControl::getInstancePID(BBInstance) // Purpose: Obtiene el pid del proceso asociado a la instancia // Created: 25/6/08 // // ------------------ unsigned int ProcessControl::getInstancePID(BBInstance myinstance) { qDebug() << "ProcessControl::getInstancePID: begin:"; #ifndef WIN32 std::string command = std::string("ps -C bbackupd -o pid,uid,command --no-heading"); qDebug() << "ProcessControl::getInstancePID: comando solicitado:" << command.c_str(); QProcess myprocess; myprocess.start(command.c_str()); if (!myprocess.waitForFinished()) { myprocess.close(); return 0; } while (!myprocess.atEnd()) { char buf[1024]; qint64 length = myprocess.readLine(buf,sizeof(buf)); if (length != -1) { QString mystring(buf); QRegExp regex("^\\s*(\\d*)\\s*(\\d*)\\s*((\\w|/)*)\\s((\\w|/|\\.)*).*$"); qDebug() << "ProcessControl::getInstancePID: Parsing line:" << mystring; if (regex.exactMatch(mystring)) { //Comparar, y si es igual devolver QStringList strlist = regex.capturedTexts(); qDebug() << "ProcessControl::getInstancePID: lista:" << strlist; if ((myinstance.getConfigPath().absoluteFilePath() == QFileInfo(strlist.at(5)).absoluteFilePath()) && (ProcessControl::userNamefromUID(strlist.at(2).toUInt()) == myinstance.getUserName()) ) { qDebug() << "Encontrado!"; myprocess.close(); return strlist.at(1).toUInt(); } else { qDebug() << "linea incorrecta" << strlist.at(5) << myinstance.getConfigPath().absoluteFilePath() << strlist.at(2).toUInt() << myinstance.getUserName(); } } else { qDebug() << "ProcessControl::getInstancePID: Error en la expresion regular"; } } else break; } qDebug() << "No se encontro el proceso"; myprocess.close(); return 0; #else std::list<int> listapids = getPidProcessByName("bbackupd.exe"); //Para cada pid: for (std::list<int>::const_iterator i = listapids.begin(); i!= listapids.end(); i++) { // Comprobar si el uid es el usuario actual // Comprobar que el parametro es el fichero de configuraci�n que nos interesa qDebug() << "ProcessControl::getInstancePID: Iterando sobre un proceso"; //if(getConfigPath(*i) == QString(myinstance.getConfigPath().absolutePath()) if(QFileInfo(QFileInfo(getBinaryPath(*i))) == myinstance.getBinaryPath() && getPIDUserName(*i) == myinstance.getUserName()) { return *i; } } return 0; #endif }
const AudioFileModel& AnalyzeTask::analyzeMediaFile(const QString &filePath, AudioFileModel &audioFile) { //bool skipNext = false; QPair<quint32, quint32> id_val(UINT_MAX, UINT_MAX); quint32 coverType = UINT_MAX; QByteArray coverData; QStringList params; params << L1S("--Language=raw") << L1S("--Output=XML") << L1S("--Full") << L1S("--Cover_Data=base64"); params << QDir::toNativeSeparators(filePath); QProcess process; MUtils::init_process(process, QFileInfo(m_mediaInfoBin).absolutePath()); process.start(m_mediaInfoBin, params); QByteArray data; data.reserve(16384); if(!process.waitForStarted()) { qWarning("MediaInfo process failed to create!"); qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData()); process.kill(); process.waitForFinished(-1); return audioFile; } while(process.state() != QProcess::NotRunning) { if(MUTILS_BOOLIFY(m_abortFlag)) { process.kill(); qWarning("Process was aborted on user request!"); break; } if(!process.waitForReadyRead()) { if(process.state() == QProcess::Running) { qWarning("MediaInfo time out. Killing the process now!"); process.kill(); process.waitForFinished(-1); break; } } forever { const QByteArray dataNext = process.readAll(); if (dataNext.isEmpty()) { break; /*no more input data*/ } data += dataNext.trimmed(); } } process.waitForFinished(); if (process.state() != QProcess::NotRunning) { process.kill(); process.waitForFinished(-1); } while (!process.atEnd()) { const QByteArray dataNext = process.readAll(); if (dataNext.isEmpty()) { break; /*no more input data*/ } data += dataNext.trimmed(); } #if MUTILS_DEBUG qDebug("-----BEGIN MEDIAINFO-----\n%s\n-----END MEDIAINFO-----", data.constData()); #endif //MUTILS_DEBUG return parseMediaInfo(data, audioFile); }