📄 qprocess.cpp
字号:
Q_D(QProcess); if (d->processState == QProcess::NotRunning) return false; if (d->processChannel == QProcess::StandardOutput && d->standardOutputClosed) return false; if (d->processChannel == QProcess::StandardError && d->standardErrorClosed) return false; return d->waitForReadyRead(msecs);}/*! \reimp*/bool QProcess::waitForBytesWritten(int msecs){ Q_D(QProcess); if (d->processState == QProcess::NotRunning) return false; if (d->processState == QProcess::Starting) { QTime stopWatch; stopWatch.start(); bool started = waitForStarted(msecs); if (!started) return false; if (msecs != -1) msecs -= stopWatch.elapsed(); } return d->waitForBytesWritten(msecs);}/*! Blocks until the process has finished and the finished() signal has been emitted, or until \a msecs milliseconds have passed. Returns true if the process finished; otherwise returns false (if the operation timed out or if an error occurred). This function can operate without an event loop. It is useful when writing non-GUI applications and when performing I/O operations in a non-GUI thread. \warning Calling this function from the main (GUI) thread might cause your user interface to freeze. If msecs is -1, this function will not time out. \sa finished(), waitForStarted(), waitForReadyRead(), waitForBytesWritten()*/bool QProcess::waitForFinished(int msecs){ Q_D(QProcess); if (d->processState == QProcess::NotRunning) return false; if (d->processState == QProcess::Starting) { QTime stopWatch; stopWatch.start(); bool started = waitForStarted(msecs); if (!started) return false; if (msecs != -1) msecs -= stopWatch.elapsed(); } return d->waitForFinished(msecs);}/*! Sets the current state of the QProcess to the \a state specified. \sa state()*/void QProcess::setProcessState(ProcessState state){ Q_D(QProcess); d->processState = state;}/*! This function is called in the child process context just before the program is executed on Unix or Mac OS X (i.e., after \e fork(), but before \e execve()). Reimplement this function to do last minute initialization of the child process. Example: \code class SandboxProcess : public QProcess { ... protected: void setupChildProcess(); ... }; void SandboxProcess::setupChildProcess() { // Drop all privileges in the child process, and enter // a chroot jail. #if defined Q_OS_UNIX ::setgroups(0, 0); ::chroot("/etc/safe"); ::chdir("/"); ::setgid(safeGid); ::setuid(safeUid); ::umask(0); #endif } \endcode \warning This function is called by QProcess on Unix and Mac OS X only. On Windows, it is not called.*/void QProcess::setupChildProcess(){}/*! \reimp*/qint64 QProcess::readData(char *data, qint64 maxlen){ Q_D(QProcess); QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError) ? &d->errorReadBuffer : &d->outputReadBuffer; if (maxlen == 1) { int c = readBuffer->getChar(); if (c == -1) {#if defined QPROCESS_DEBUG qDebug("QProcess::readData(%p \"%s\", %d) == -1", data, qt_prettyDebug(data, maxlen, 1).constData(), 1);#endif return -1; } *data = (char) c;#if defined QPROCESS_DEBUG qDebug("QProcess::readData(%p \"%s\", %d) == 1", data, qt_prettyDebug(data, maxlen, 1).constData(), 1);#endif return 1; } qint64 bytesToRead = qint64(qMin(readBuffer->size(), (int)maxlen)); qint64 readSoFar = 0; while (readSoFar < bytesToRead) { char *ptr = readBuffer->readPointer(); int bytesToReadFromThisBlock = qMin<qint64>(bytesToRead - readSoFar, readBuffer->nextDataBlockSize()); memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock); readSoFar += bytesToReadFromThisBlock; readBuffer->free(bytesToReadFromThisBlock); }#if defined QPROCESS_DEBUG qDebug("QProcess::readData(%p \"%s\", %lld) == %lld", data, qt_prettyDebug(data, readSoFar, 16).constData(), maxlen, readSoFar);#endif return readSoFar;}/*! \reimp*/qint64 QProcess::writeData(const char *data, qint64 len){ Q_D(QProcess); if (d->writeChannelClosing) {#if defined QPROCESS_DEBUG qDebug("QProcess::writeData(%p \"%s\", %lld) == 0 (write channel closing)", data, qt_prettyDebug(data, len, 16).constData(), len);#endif return 0; } if (len == 1) { d->writeBuffer.putChar(*data); if (d->writeSocketNotifier) d->writeSocketNotifier->setEnabled(true);#if defined QPROCESS_DEBUG qDebug("QProcess::writeData(%p \"%s\", %lld) == 1 (written to buffer)", data, qt_prettyDebug(data, len, 16).constData(), len);#endif return 1; } char *dest = d->writeBuffer.reserve(len); memcpy(dest, data, len); if (d->writeSocketNotifier) d->writeSocketNotifier->setEnabled(true);#if defined QPROCESS_DEBUG qDebug("QProcess::writeData(%p \"%s\", %lld) == %lld (written to buffer)", data, qt_prettyDebug(data, len, 16).constData(), len, len);#endif return len;}/*! Regardless of the current read channel, this function returns all data available from the standard output of the process as a QByteArray. \sa readyReadStandardOutput(), readAllStandardError(), readChannel(), setReadChannel()*/QByteArray QProcess::readAllStandardOutput(){ ProcessChannel tmp = readChannel(); setReadChannel(StandardOutput); QByteArray data = readAll(); setReadChannel(tmp); return data;}/*! Regardless of the current read channel, this function returns all data available from the standard error of the process as a QByteArray. \sa readyReadStandardError(), readAllStandardOutput(), readChannel(), setReadChannel()*/QByteArray QProcess::readAllStandardError(){ ProcessChannel tmp = readChannel(); setReadChannel(StandardError); QByteArray data = readAll(); setReadChannel(tmp); return data;}/*! Starts the program \a program in a new process, passing the command line arguments in \a arguments. The OpenMode is set to \a mode. QProcess will immediately enter the Starting state. If the process starts successfully, QProcess will emit started(); otherwise, error() will be emitted. On Windows, arguments that contain spaces are wrapped in quotes. \sa pid(), started()*/void QProcess::start(const QString &program, const QStringList &arguments, OpenMode mode){ Q_D(QProcess); if (d->processState != NotRunning) { qWarning("QProcess::start() called when a process is already running."); return; } d->outputReadBuffer.clear(); d->errorReadBuffer.clear(); setOpenMode(mode); d->writeChannelClosing = false; d->standardOutputClosed = false; d->standardErrorClosed = false; d->program = program; d->arguments = arguments; d->exitCode = 0; d->exitStatus = NormalExit; d->processError = QProcess::UnknownError; setErrorString(tr("Unknown error")); d->startProcess();}static QStringList parseCombinedArgString(const QString &program){ QStringList args; QString tmp; int quoteCount = 0; bool inQuote = false; // handle quoting. tokens can be surrounded by double quotes // "hello world". three consecutive double quotes represent // the quote character itself. for (int i = 0; i < program.size(); ++i) { if (program.at(i) == QLatin1Char('"')) { ++quoteCount; if (quoteCount == 3) { // third consecutive quote quoteCount = 0; tmp += program.at(i); } continue; } if (quoteCount) { if (quoteCount == 1) inQuote = !inQuote; quoteCount = 0; } if (!inQuote && program.at(i).isSpace()) { if (!tmp.isEmpty()) { args += tmp; tmp.clear(); } } else { tmp += program.at(i); } } if (!tmp.isEmpty()) args += tmp; return args;}/*! \overload Starts the program \a program in a new process. \a program is a single string of text containing both the program name and its arguments. The arguments are separated by one or more spaces. For example: \code QProcess process; process.start("del /s *.txt"); // same as process.start("del", QStringList() << "/s" << "*.txt"); ... \endcode The \a program string can also contain quotes, to ensure that arguments containing spaces are correctly supplied to the new process. For example: \code QProcess process; process.start("dir \"My Documents\""); \endcode Note that, on Windows, quotes need to be both escaped and quoted. For example, the above code would be specified in the following way to ensure that \c{"My Documents"} is used as the argument to the \c dir executable: \code QProcess process; process.start("dir \"\"\"My Documents\"\"\""); \endcode The OpenMode is set to \a mode.*/void QProcess::start(const QString &program, OpenMode mode){ QStringList args = parseCombinedArgString(program); QString prog = args.first(); args.removeFirst(); start(prog, args, mode);}/*! Attempts to terminate the process. The process may not exit as a result of calling this function (it is given the chance to prompt the user for any unsaved files, etc). On Windows, terminate() posts a WM_CLOSE message to the process, and on Unix and Mac OS X the SIGTERM signal is sent. \sa kill()*/void QProcess::terminate(){ Q_D(QProcess); d->terminateProcess();}/*! Kills the current process, causing it to exit immediately. On Windows, kill() uses TerminateProcess, and on Unix and Mac OS X, the SIGKILL signal is sent to the process. \sa terminate()*/void QProcess::kill(){ Q_D(QProcess); d->killProcess();}/*! Returns the exit code of the last process that finished.*/int QProcess::exitCode() const{ Q_D(const QProcess); return d->exitCode;}/*! \since 4.1 Returns the exit status of the last process that finished. On Windows, if the process was terminated with TerminateProcess() from another application this function will still return NormalExit unless the exit code is less than 0.*/QProcess::ExitStatus QProcess::exitStatus() const{ Q_D(const QProcess); return d->exitStatus;}/*! Starts the program \a program with the arguments \a arguments in a new process, waits for it to finish, and then returns the exit code of the process. Any data the new process writes to the console is forwarded to the calling process. The environment and working directory are inherited by the calling process. On Windows, arguments that contain spaces are wrapped in quotes.*/int QProcess::execute(const QString &program, const QStringList &arguments){ QProcess process; process.setReadChannelMode(ForwardedChannels); process.start(program, arguments); process.waitForFinished(-1); return process.exitCode();}/*! \overload Starts the program \a program in a new process. \a program is a single string of text containing both the program name and its arguments. The arguments are separated by one or more spaces.*/int QProcess::execute(const QString &program){ QProcess process; process.setReadChannelMode(ForwardedChannels); process.start(program); process.waitForFinished(-1); return process.exitCode();}/*! Starts the program \a program with the arguments \a arguments in a new process, and detaches from it. Returns true on success; otherwise returns false. If the calling process exits, the detached process will continue to live. On Unix, the started process will run in its own session and act like a daemon. On Windows, it will run as a regular standalone process. On Windows, arguments that contain spaces are wrapped in quotes.*/bool QProcess::startDetached(const QString &program, const QStringList &arguments){ return QProcessPrivate::startDetached(program, arguments);}/*! \overload Starts the program \a program in a new process. \a program is a single string of text containing both the program name and its arguments. The arguments are separated by one or more spaces. The \a program string can also contain quotes, to ensure that arguments containing spaces are correctly supplied to the new process.*/bool QProcess::startDetached(const QString &program){ QStringList args = parseCombinedArgString(program); QString prog = args.first(); args.removeFirst(); return QProcessPrivate::startDetached(prog, args);}#ifdef Q_OS_MAC# include <crt_externs.h># define environ (*_NSGetEnviron())#elif !defined(Q_OS_WIN) extern char **environ;#endif/*! \since 4.1 Returns the environment of the calling process as a list of key=value pairs. Example: \code QStringList environment = QProcess::systemEnvironment(); // environment = {"PATH=/usr/bin:/usr/local/bin", "USER=greg", "HOME=/home/greg"} \endcode \sa environment(), setEnvironment()*/QStringList QProcess::systemEnvironment(){ QStringList tmp; char *entry = 0; int count = 0; while ((entry = environ[count++])) tmp << QString::fromLocal8Bit(entry); return tmp;}#include "moc_qprocess.cpp"#endif // QT_NO_PROCESS
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -