?? qprocess.cpp
字號:
/******************************************************************************** Copyright (C) 1992-2006 Trolltech ASA. All rights reserved.**** This file is part of the QtCore module of the Qt Toolkit.**** This file may be used under the terms of the GNU General Public** License version 2.0 as published by the Free Software Foundation** and appearing in the file LICENSE.GPL included in the packaging of** this file. Please review the following information to ensure GNU** General Public Licensing requirements will be met:** http://www.trolltech.com/products/qt/opensource.html**** If you are unsure which license is appropriate for your use, please** review the following information:** http://www.trolltech.com/products/qt/licensing.html or contact the** sales department at sales@trolltech.com.**** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.******************************************************************************///#define QPROCESS_DEBUG#if defined QPROCESS_DEBUG#include <qdebug.h>#include <qstring.h>#include <ctype.h>/* Returns a human readable representation of the first \a len characters in \a data.*/static QByteArray qt_prettyDebug(const char *data, int len, int maxSize){ if (!data) return "(null)"; QByteArray out; for (int i = 0; i < len && i < maxSize; ++i) { char c = data[i]; if (isprint(c)) { out += c; } else switch (c) { case '\n': out += "\\n"; break; case '\r': out += "\\r"; break; case '\t': out += "\\t"; break; default: char buf[5]; qsnprintf(buf, sizeof(buf), "\\%3o", c); buf[4] = '\0'; out += QString::fromLatin1(buf); } } if (len < maxSize) out += "..."; return out;}#endif#include "qprocess.h"#include "qprocess_p.h"#include <qbytearray.h>#include <qdatetime.h>#include <qcoreapplication.h>#include <qsocketnotifier.h>#include <qtimer.h>#ifdef Q_WS_WIN#include <private/qwineventnotifier_p.h>#endif#ifndef QT_NO_PROCESS/*! \class QProcess \brief The QProcess class is used to start external programs and to communicate with them. \ingroup io \ingroup misc \mainclass \reentrant To start a process, pass the name and command line arguments of the program you want to run as arguments to start(). For example: \quotefromfile snippets/qprocess/qprocess-simpleexecution.cpp \skipto parent \printline parent \dots \skipto program \printline program \skipto QStringList \printuntil start QProcess then enters the \l Starting state, and when the program has started, QProcess enters the \l Running state and emits started(). QProcess allows you to treat a process as a sequential I/O device. You can write to and read from the process just as you would access a network connection using QTcpSocket. You can then write to the process's standard input by calling write(), and read the standard output by calling read(), readLine(), and getChar(). Because it inherits QIODevice, QProcess can also be used as an input source for QXmlReader, or for generating data to be uploaded using QFtp. When the process exits, QProcess reenters the \l NotRunning state (the initial state), and emits finished(). The finished() signal provides the exit code and exit status of the process as arguments, and you can also call exitCode() to obtain the exit code of the last process that finished, and exitStatus() to obtain its exit status. If an error occurs at any point in time, QProcess will emit the error() signal. You can also call error() to find the type of error that occurred last, and state() to find the current process state. Processes have two predefined output channels: The standard output channel (\c stdout) supplies regular console output, and the standard error channel (\c stderr) usually supplies the errors that are printed by the process. These channels represent two separate streams of data. You can toggle between them by calling setReadChannel(). QProcess emits readyRead() when data is available on the current read channel. It also emits readyReadStandardOutput() when new standard output data is available, and when new standard error data is available, readyReadStandardError() is emitted. Instead of calling read(), readLine(), or getChar(), you can explicitly read all data from either of the two channels by calling readAllStandardOutput() or readAllStandardError(). The terminology for the channels can be misleading. Be aware that the process's output channels correspond to QProcess's \e read channels, whereas the process's input channels correspond to QProcess's \e write channels. This is because what we read using QProcess is the process's output, and what we write becomes the process's input. QProcess can merge the two output channels, so that standard output and standard error data from the running process both use the standard output channel. Call setProcessChannelMode() with MergedChannels before starting the process to activative this feature. You also have the option of forwarding the output of the running process to the calling, main process, by passing ForwardedChannels as the argument. Certain processes need special environment settings in order to operate. You can set environment variables for your process by calling setEnvironment(). To set a working directory, call setWorkingDirectory(). By default, processes are run in the current working directory of the calling process. QProcess provides a set of functions which allow it to be used without an event loop, by suspending the calling thread until certain signals are emitted: \list \o waitForStarted() blocks until the process has started. \o waitForReadyRead() blocks until new data is available for reading on the current read channel. \o waitForBytesWritten() blocks until one payload of data has been written to the process. \o waitForFinished() blocks until the process has finished. \endlist Calling these functions from the main thread (the thread that calls QApplication::exec()) may cause your user interface to freeze. The following example runs \c gzip to compress the string "Qt rocks!", without an event loop: \quotefromfile snippets/process/process.cpp \skipto QProcess gzip; \printuntil result = gzip.readAll(); \sa QBuffer, QFile, QTcpSocket*//*! \enum QProcess::ProcessChannel This enum describes the process channels used by the running process. Pass one of these values to setReadChannel() to set the current read channel of QProcess. \value StandardOutput The standard output (stdout) of the running process. \value StandardError The standard error (stderr) of the running process. \sa setReadChannel()*//*! \enum QProcess::ProcessChannelMode This enum describes the process channel modes of QProcess. Pass one of these values to setProcessChannelMode() to set the current read channel mode. \value SeparateChannels QProcess manages the output of the running process, keeping standard output and standard error data in separate internal buffers. You can select the QProcess's current read channel by calling setReadChannel(). This is the default channel mode of QProcess. \value MergedChannels QProcess merges the output of the running process into the standard output channel (\c stdout). The standard error channel (\c stderr) will not receive any data. The standard output and standard error data of the running process are interleaved. \value ForwardedChannels QProcess forwards the output of the running process onto the main process. Anything the child process writes to its standard output and standard error will be written to the standard output and standard error of the main process. \sa setReadChannelMode()*//*! \enum QProcess::ProcessError This enum describes the different types of errors that are reported by QProcess. \value FailedToStart The process failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program. \value Crashed The process crashed some time after starting successfully. \value Timedout The last waitFor...() function timed out. The state of QProcess is unchanged, and you can try calling waitFor...() again. \value WriteError An error occurred when attempting to write to the process. For example, the process may not be running, or it may have closed its input channel. \value ReadError An error occurred when attempting to read from the process. For example, the process may not be running. \value UnknownError An unknown error occurred. This is the default return value of error(). \sa error()*//*! \enum QProcess::ProcessState This enum describes the different states of QProcess. \value NotRunning The process is not running. \value Starting The process is starting, but the program has not yet been invoked. \value Running The process is running and is ready for reading and writing. \sa state()*//*! \enum QProcess::ExitStatus This enum describes the different exit statuses of QProcess. \value NormalExit The process exited normally. \value CrashExit The process crashed. \sa exitStatus()*//*! \fn void QProcess::error(QProcess::ProcessError error) This signal is emitted when an error occurs with the process. The specified \a error describes the type of error that occurred.*//*! \fn void QProcess::started() This signal is emitted by QProcess when the process has started, and state() returns \l Running.*//*! \fn void QProcess::stateChanged(QProcess::ProcessState newState) This signal is emitted whenever the state of QProcess changes. The \a newState argument is the state QProcess changed to.*//*! \fn void QProcess::finished(int exitCode) \obsolete \overload Use finished(int exitCode, QProcess::ExitStatus status) instead.*//*! \fn void QProcess::finished(int exitCode, QProcess::ExitStatus exitStatus) This signal is emitted when the process finishes. \a exitCode is the exit code of the process, and \a exitStatus is the exit status. After the process has finished, the buffers in QProcess are still intact. You can still read any data that the process may have written before it finished. \sa exitStatus()*//*! \fn void QProcess::readyReadStandardOutput() This signal is emitted when the process has made new data available through its standard output channel (\c stdout). It is emitted regardless of the current \l{readChannel()}{read channel}. \sa readAllStandardOutput(), readChannel()*//*! \fn void QProcess::readyReadStandardError() This signal is emitted when the process has made new data available through its standard error channel (\c stderr). It is emitted regardless of the current \l{readChannel()}{read channel}. \sa readAllStandardError(), readChannel()*//*! \internal*/QProcessPrivate::QProcessPrivate(){ processChannel = QProcess::StandardOutput; processChannelMode = QProcess::SeparateChannels; processError = QProcess::UnknownError; processState = QProcess::NotRunning; pid = 0; sequenceNumber = 0; exitCode = 0; exitStatus = QProcess::NormalExit; startupSocketNotifier = 0; deathNotifier = 0; notifier = 0; pipeWriter = 0; childStartedPipe[0] = INVALID_Q_PIPE; childStartedPipe[1] = INVALID_Q_PIPE; deathPipe[0] = INVALID_Q_PIPE; deathPipe[1] = INVALID_Q_PIPE; exitCode = 0; crashed = false; emittedReadyRead = false; emittedBytesWritten = false;#ifdef Q_WS_WIN pipeWriter = 0; processFinishedNotifier = 0;#endif // Q_WS_WIN#ifdef Q_OS_UNIX serial = 0;#endif}/*! \internal*/QProcessPrivate::~QProcessPrivate(){ if (stdinChannel.process) stdinChannel.process->stdoutChannel.clear(); if (stdoutChannel.process) stdoutChannel.process->stdinChannel.clear();}/*! \internal*/void QProcessPrivate::cleanup(){ processState = QProcess::NotRunning;#ifdef Q_OS_WIN if (pid) { CloseHandle(pid->hThread); CloseHandle(pid->hProcess); delete pid; pid = 0; } if (processFinishedNotifier) { processFinishedNotifier->setEnabled(false); delete processFinishedNotifier; processFinishedNotifier = 0; }#endif pid = 0; sequenceNumber = 0; if (stdoutChannel.notifier) { stdoutChannel.notifier->setEnabled(false); delete stdoutChannel.notifier; stdoutChannel.notifier = 0; } if (stderrChannel.notifier) { stderrChannel.notifier->setEnabled(false); delete stderrChannel.notifier; stderrChannel.notifier = 0; } if (stdinChannel.notifier) { stdinChannel.notifier->setEnabled(false); delete stdinChannel.notifier; stdinChannel.notifier = 0; } if (startupSocketNotifier) { startupSocketNotifier->setEnabled(false); delete startupSocketNotifier;
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -