src/corelib/io/qprocess.cpp
changeset 0 1918ee327afb
child 3 41300fa6a67c
equal deleted inserted replaced
-1:000000000000 0:1918ee327afb
       
     1 /****************************************************************************
       
     2 **
       
     3 ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
       
     4 ** All rights reserved.
       
     5 ** Contact: Nokia Corporation (qt-info@nokia.com)
       
     6 **
       
     7 ** This file is part of the QtCore module of the Qt Toolkit.
       
     8 **
       
     9 ** $QT_BEGIN_LICENSE:LGPL$
       
    10 ** No Commercial Usage
       
    11 ** This file contains pre-release code and may not be distributed.
       
    12 ** You may use this file in accordance with the terms and conditions
       
    13 ** contained in the Technology Preview License Agreement accompanying
       
    14 ** this package.
       
    15 **
       
    16 ** GNU Lesser General Public License Usage
       
    17 ** Alternatively, this file may be used under the terms of the GNU Lesser
       
    18 ** General Public License version 2.1 as published by the Free Software
       
    19 ** Foundation and appearing in the file LICENSE.LGPL included in the
       
    20 ** packaging of this file.  Please review the following information to
       
    21 ** ensure the GNU Lesser General Public License version 2.1 requirements
       
    22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
       
    23 **
       
    24 ** In addition, as a special exception, Nokia gives you certain additional
       
    25 ** rights.  These rights are described in the Nokia Qt LGPL Exception
       
    26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
       
    27 **
       
    28 ** If you have questions regarding the use of this file, please contact
       
    29 ** Nokia at qt-info@nokia.com.
       
    30 **
       
    31 **
       
    32 **
       
    33 **
       
    34 **
       
    35 **
       
    36 **
       
    37 **
       
    38 ** $QT_END_LICENSE$
       
    39 **
       
    40 ****************************************************************************/
       
    41 
       
    42 //#define QPROCESS_DEBUG
       
    43 
       
    44 #if defined QPROCESS_DEBUG
       
    45 #include <qdebug.h>
       
    46 #include <qstring.h>
       
    47 #include <ctype.h>
       
    48 #if !defined(Q_OS_WINCE)
       
    49 #include <errno.h>
       
    50 #endif
       
    51 
       
    52 QT_BEGIN_NAMESPACE
       
    53 /*
       
    54     Returns a human readable representation of the first \a len
       
    55     characters in \a data.
       
    56 */
       
    57 static QByteArray qt_prettyDebug(const char *data, int len, int maxSize)
       
    58 {
       
    59     if (!data) return "(null)";
       
    60     QByteArray out;
       
    61     for (int i = 0; i < len && i < maxSize; ++i) {
       
    62         char c = data[i];
       
    63         if (isprint(c)) {
       
    64             out += c;
       
    65         } else switch (c) {
       
    66         case '\n': out += "\\n"; break;
       
    67         case '\r': out += "\\r"; break;
       
    68         case '\t': out += "\\t"; break;
       
    69         default:
       
    70             char buf[5];
       
    71             qsnprintf(buf, sizeof(buf), "\\%3o", c);
       
    72             buf[4] = '\0';
       
    73             out += QByteArray(buf);
       
    74         }
       
    75     }
       
    76 
       
    77     if (len < maxSize)
       
    78         out += "...";
       
    79 
       
    80     return out;
       
    81 }
       
    82 
       
    83 QT_END_NAMESPACE
       
    84 
       
    85 #endif
       
    86 
       
    87 #include "qprocess.h"
       
    88 #include "qprocess_p.h"
       
    89 
       
    90 #include <qbytearray.h>
       
    91 #include <qdatetime.h>
       
    92 #include <qcoreapplication.h>
       
    93 #include <qsocketnotifier.h>
       
    94 #include <qtimer.h>
       
    95 
       
    96 #ifdef Q_WS_WIN
       
    97 #include <private/qwineventnotifier_p.h>
       
    98 #endif
       
    99 
       
   100 #ifdef Q_OS_SYMBIAN
       
   101 #include <e32std.h>
       
   102 #endif
       
   103 
       
   104 #ifndef QT_NO_PROCESS
       
   105 
       
   106 QT_BEGIN_NAMESPACE
       
   107 
       
   108 /*!
       
   109     \class QProcessEnvironment
       
   110 
       
   111     \brief The QProcessEnvironment class holds the environment variables that
       
   112     can be passed to a program.
       
   113 
       
   114     \ingroup io
       
   115     \ingroup misc
       
   116     \mainclass
       
   117     \reentrant
       
   118     \since 4.6
       
   119 
       
   120     A process's environment is composed of a set of key=value pairs known as
       
   121     environment variables. The QProcessEnvironment class wraps that concept
       
   122     and allows easy manipulation of those variables. It's meant to be used
       
   123     along with QProcess, to set the environment for child processes. It
       
   124     cannot be used to change the current process's environment.
       
   125 
       
   126     The environment of the calling process can be obtained using
       
   127     QProcessEnvironment::systemEnvironment().
       
   128 
       
   129     On Unix systems, the variable names are case-sensitive. For that reason,
       
   130     this class will not touch the names of the variables. Note as well that
       
   131     Unix environment allows both variable names and contents to contain arbitrary
       
   132     binary data (except for the NUL character), but this is not supported by
       
   133     QProcessEnvironment. This class only supports names and values that are
       
   134     encodable by the current locale settings (see QTextCodec::codecForLocale).
       
   135 
       
   136     On Windows, the variable names are case-insensitive. Therefore,
       
   137     QProcessEnvironment will always uppercase the names and do case-insensitive
       
   138     comparisons.
       
   139 
       
   140     On Windows CE, the concept of environment does not exist. This class will
       
   141     keep the values set for compatibility with other platforms, but the values
       
   142     set will have no effect on the processes being created.
       
   143 
       
   144     \sa QProcess, QProcess::systemEnvironment(), QProcess::setProcessEnvironment()
       
   145 */
       
   146 #ifdef Q_OS_WIN
       
   147 static inline QProcessEnvironmentPrivate::Unit prepareName(const QString &name)
       
   148 { return name.toUpper(); }
       
   149 static inline QProcessEnvironmentPrivate::Unit prepareName(const QByteArray &name)
       
   150 { return QString::fromLocal8Bit(name).toUpper(); }
       
   151 static inline QString nameToString(const QProcessEnvironmentPrivate::Unit &name)
       
   152 { return name; }
       
   153 static inline QProcessEnvironmentPrivate::Unit prepareValue(const QString &value)
       
   154 { return value; }
       
   155 static inline QProcessEnvironmentPrivate::Unit prepareValue(const QByteArray &value)
       
   156 { return QString::fromLocal8Bit(value); }
       
   157 static inline QString valueToString(const QProcessEnvironmentPrivate::Unit &value)
       
   158 { return value; }
       
   159 static inline QByteArray valueToByteArray(const QProcessEnvironmentPrivate::Unit &value)
       
   160 { return value.toLocal8Bit(); }
       
   161 #else
       
   162 static inline QProcessEnvironmentPrivate::Unit prepareName(const QByteArray &name)
       
   163 { return name; }
       
   164 static inline QProcessEnvironmentPrivate::Unit prepareName(const QString &name)
       
   165 { return name.toLocal8Bit(); }
       
   166 static inline QString nameToString(const QProcessEnvironmentPrivate::Unit &name)
       
   167 { return QString::fromLocal8Bit(name); }
       
   168 static inline QProcessEnvironmentPrivate::Unit prepareValue(const QByteArray &value)
       
   169 { return value; }
       
   170 static inline QProcessEnvironmentPrivate::Unit prepareValue(const QString &value)
       
   171 { return value.toLocal8Bit(); }
       
   172 static inline QString valueToString(const QProcessEnvironmentPrivate::Unit &value)
       
   173 { return QString::fromLocal8Bit(value); }
       
   174 static inline QByteArray valueToByteArray(const QProcessEnvironmentPrivate::Unit &value)
       
   175 { return value; }
       
   176 #endif
       
   177 
       
   178 template<> void QSharedDataPointer<QProcessEnvironmentPrivate>::detach()
       
   179 {
       
   180     if (d && d->ref == 1)
       
   181         return;
       
   182     QProcessEnvironmentPrivate *x = (d ? new QProcessEnvironmentPrivate(*d)
       
   183                                      : new QProcessEnvironmentPrivate);
       
   184     x->ref.ref();
       
   185     if (d && !d->ref.deref())
       
   186         delete d;
       
   187     d = x;
       
   188 }
       
   189 
       
   190 QStringList QProcessEnvironmentPrivate::toList() const
       
   191 {
       
   192     QStringList result;
       
   193     QHash<Unit, Unit>::ConstIterator it = hash.constBegin(),
       
   194                                     end = hash.constEnd();
       
   195     for ( ; it != end; ++it) {
       
   196         QString data = nameToString(it.key());
       
   197         QString value = valueToString(it.value());
       
   198         data.reserve(data.length() + value.length() + 1);
       
   199         data.append(QLatin1Char('='));
       
   200         data.append(value);
       
   201         result << data;
       
   202     }
       
   203     return result;
       
   204 }
       
   205 
       
   206 QProcessEnvironment QProcessEnvironmentPrivate::fromList(const QStringList &list)
       
   207 {
       
   208     QProcessEnvironment env;
       
   209     QStringList::ConstIterator it = list.constBegin(),
       
   210                               end = list.constEnd();
       
   211     for ( ; it != end; ++it) {
       
   212         int pos = it->indexOf(QLatin1Char('='));
       
   213         if (pos < 1)
       
   214             continue;
       
   215 
       
   216         QString value = it->mid(pos + 1);
       
   217         QString name = *it;
       
   218         name.truncate(pos);
       
   219         env.insert(name, value);
       
   220     }
       
   221     return env;
       
   222 }
       
   223 
       
   224 /*!
       
   225     Creates a new QProcessEnvironment object. This constructor creates an
       
   226     empty environment. If set on a QProcess, this will cause the current
       
   227     environment variables to be removed.
       
   228 */
       
   229 QProcessEnvironment::QProcessEnvironment()
       
   230     : d(0)
       
   231 {
       
   232 }
       
   233 
       
   234 /*!
       
   235     Frees the resources associated with this QProcessEnvironment object.
       
   236 */
       
   237 QProcessEnvironment::~QProcessEnvironment()
       
   238 {
       
   239 }
       
   240 
       
   241 /*!
       
   242     Creates a QProcessEnvironment object that is a copy of \a other.
       
   243 */
       
   244 QProcessEnvironment::QProcessEnvironment(const QProcessEnvironment &other)
       
   245     : d(other.d)
       
   246 {
       
   247 }
       
   248 
       
   249 /*!
       
   250     Copies the contents of the \a other QProcessEnvironment object into this
       
   251     one.
       
   252 */
       
   253 QProcessEnvironment &QProcessEnvironment::operator=(const QProcessEnvironment &other)
       
   254 {
       
   255     d = other.d;
       
   256     return *this;
       
   257 }
       
   258 
       
   259 /*!
       
   260     \fn bool QProcessEnvironment::operator !=(const QProcessEnvironment &other) const
       
   261 
       
   262     Returns true if this and the \a other QProcessEnvironment objects are different.
       
   263 
       
   264     \sa operator==()
       
   265 */
       
   266 
       
   267 /*!
       
   268     Returns true if this and the \a other QProcessEnvironment objects are equal.
       
   269 
       
   270     Two QProcessEnvironment objects are considered equal if they have the same
       
   271     set of key=value pairs. The comparison of keys is done case-sensitive on
       
   272     platforms where the environment is case-sensitive.
       
   273 
       
   274     \sa operator!=(), contains()
       
   275 */
       
   276 bool QProcessEnvironment::operator==(const QProcessEnvironment &other) const
       
   277 {
       
   278     return d->hash == other.d->hash;
       
   279 }
       
   280 
       
   281 /*!
       
   282     Returns true if this QProcessEnvironment object is empty: that is
       
   283     there are no key=value pairs set.
       
   284 
       
   285     \sa clear(), systemEnvironment(), insert()
       
   286 */
       
   287 bool QProcessEnvironment::isEmpty() const
       
   288 {
       
   289     return d ? d->hash.isEmpty() : true;
       
   290 }
       
   291 
       
   292 /*!
       
   293     Removes all key=value pairs from this QProcessEnvironment object, making
       
   294     it empty.
       
   295 
       
   296     \sa isEmpty(), systemEnvironment()
       
   297 */
       
   298 void QProcessEnvironment::clear()
       
   299 {
       
   300     if (d)
       
   301         d->hash.clear();
       
   302 }
       
   303 
       
   304 /*!
       
   305     Returns true if the environment variable of name \a name is found in
       
   306     this QProcessEnvironment object.
       
   307 
       
   308     On Windows, variable names are case-insensitive, so the key is converted
       
   309     to uppercase before searching. On other systems, names are case-sensitive
       
   310     so no trasformation is applied.
       
   311 
       
   312     \sa insert(), value()
       
   313 */
       
   314 bool QProcessEnvironment::contains(const QString &name) const
       
   315 {
       
   316     return d ? d->hash.contains(prepareName(name)) : false;
       
   317 }
       
   318 
       
   319 /*!
       
   320     Inserts the environment variable of name \a name and contents \a value
       
   321     into this QProcessEnvironment object. If that variable already existed,
       
   322     it is replaced by the new value.
       
   323 
       
   324     On Windows, variable names are case-insensitive, so this function always
       
   325     uppercases the variable name before inserting. On other systems, names
       
   326     are case-sensitive, so no transformation is applied.
       
   327 
       
   328     On most systems, inserting a variable with no contents will have the
       
   329     same effect for applications as if the variable had not been set at all.
       
   330     However, to guarantee that there are no incompatibilities, to remove a
       
   331     variable, please use the remove() function.
       
   332 
       
   333     \sa contains(), remove(), value()
       
   334 */
       
   335 void QProcessEnvironment::insert(const QString &name, const QString &value)
       
   336 {
       
   337     d->hash.insert(prepareName(name), prepareValue(value));
       
   338 }
       
   339 
       
   340 /*!
       
   341     Removes the environment variable identified by \a name from this
       
   342     QProcessEnvironment object. If that variable did not exist before,
       
   343     nothing happens.
       
   344 
       
   345     On Windows, variable names are case-insensitive, so the key is converted
       
   346     to uppercase before searching. On other systems, names are case-sensitive
       
   347     so no trasformation is applied.
       
   348 
       
   349     \sa contains(), insert(), value()
       
   350 */
       
   351 void QProcessEnvironment::remove(const QString &name)
       
   352 {
       
   353     if (d)
       
   354         d->hash.remove(prepareName(name));
       
   355 }
       
   356 
       
   357 /*!
       
   358     Searches this QProcessEnvironment object for a variable identified by
       
   359     \a name and returns its value. If the variable is not found in this object,
       
   360     then \a defaultValue is returned instead.
       
   361 
       
   362     On Windows, variable names are case-insensitive, so the key is converted
       
   363     to uppercase before searching. On other systems, names are case-sensitive
       
   364     so no trasformation is applied.
       
   365 
       
   366     \sa contains(), insert(), remove()
       
   367 */
       
   368 QString QProcessEnvironment::value(const QString &name, const QString &defaultValue) const
       
   369 {
       
   370     if (!d)
       
   371         return defaultValue;
       
   372 
       
   373     QProcessEnvironmentPrivate::Hash::ConstIterator it = d->hash.constFind(prepareName(name));
       
   374     if (it == d->hash.constEnd())
       
   375         return defaultValue;
       
   376 
       
   377     return valueToString(it.value());
       
   378 }
       
   379 
       
   380 /*!
       
   381     Converts this QProcessEnvironment object into a list of strings, one for
       
   382     each environment variable that is set. The environment variable's name
       
   383     and its value are separated by an equal character ('=').
       
   384 
       
   385     The QStringList contents returned by this function are suitable for use
       
   386     with the QProcess::setEnvironment function. However, it is recommended
       
   387     to use QProcess::setProcessEnvironment instead since that will avoid
       
   388     unnecessary copying of the data.
       
   389 
       
   390     \sa systemEnvironment(), QProcess::systemEnvironment(), QProcess::environment(),
       
   391         QProcess::setEnvironment()
       
   392 */
       
   393 QStringList QProcessEnvironment::toStringList() const
       
   394 {
       
   395     return d ? d->toList() : QStringList();
       
   396 }
       
   397 
       
   398 void QProcessPrivate::Channel::clear()
       
   399 {
       
   400     switch (type) {
       
   401     case PipeSource:
       
   402         Q_ASSERT(process);
       
   403         process->stdinChannel.type = Normal;
       
   404         process->stdinChannel.process = 0;
       
   405         break;
       
   406     case PipeSink:
       
   407         Q_ASSERT(process);
       
   408         process->stdoutChannel.type = Normal;
       
   409         process->stdoutChannel.process = 0;
       
   410         break;
       
   411     }
       
   412 
       
   413     type = Normal;
       
   414     file.clear();
       
   415     process = 0;
       
   416 }
       
   417 
       
   418 /*! \fn bool QProcessPrivate::startDetached(const QString &program, const QStringList &arguments, const QString &workingDirectory, qint64 *pid)
       
   419 
       
   420 \internal
       
   421  */
       
   422 
       
   423 /*!
       
   424     \class QProcess
       
   425 
       
   426     \brief The QProcess class is used to start external programs and
       
   427     to communicate with them.
       
   428 
       
   429     \ingroup io
       
   430 
       
   431     \reentrant
       
   432 
       
   433     \section1 Running a Process
       
   434 
       
   435     To start a process, pass the name and command line arguments of
       
   436     the program you want to run as arguments to start(). Arguments
       
   437     are supplied as individual strings in a QStringList.
       
   438 
       
   439     For example, the following code snippet runs the analog clock
       
   440     example in the Motif style on X11 platforms by passing strings
       
   441     containing "-style" and "motif" as two items in the list of
       
   442     arguments:
       
   443 
       
   444     \snippet doc/src/snippets/qprocess/qprocess-simpleexecution.cpp 0
       
   445     \dots
       
   446     \snippet doc/src/snippets/qprocess/qprocess-simpleexecution.cpp 1
       
   447     \snippet doc/src/snippets/qprocess/qprocess-simpleexecution.cpp 2
       
   448 
       
   449     QProcess then enters the \l Starting state, and when the program
       
   450     has started, QProcess enters the \l Running state and emits
       
   451     started().
       
   452 
       
   453     QProcess allows you to treat a process as a sequential I/O
       
   454     device. You can write to and read from the process just as you
       
   455     would access a network connection using QTcpSocket. You can then
       
   456     write to the process's standard input by calling write(), and
       
   457     read the standard output by calling read(), readLine(), and
       
   458     getChar(). Because it inherits QIODevice, QProcess can also be
       
   459     used as an input source for QXmlReader, or for generating data to
       
   460     be uploaded using QFtp.
       
   461 
       
   462     \note On Windows CE and Symbian, reading and writing to a process
       
   463     is not supported.
       
   464 
       
   465     When the process exits, QProcess reenters the \l NotRunning state
       
   466     (the initial state), and emits finished().
       
   467 
       
   468     The finished() signal provides the exit code and exit status of
       
   469     the process as arguments, and you can also call exitCode() to
       
   470     obtain the exit code of the last process that finished, and
       
   471     exitStatus() to obtain its exit status. If an error occurs at
       
   472     any point in time, QProcess will emit the error() signal. You
       
   473     can also call error() to find the type of error that occurred
       
   474     last, and state() to find the current process state.
       
   475 
       
   476     \section1 Communicating via Channels
       
   477 
       
   478     Processes have two predefined output channels: The standard
       
   479     output channel (\c stdout) supplies regular console output, and
       
   480     the standard error channel (\c stderr) usually supplies the
       
   481     errors that are printed by the process. These channels represent
       
   482     two separate streams of data. You can toggle between them by
       
   483     calling setReadChannel(). QProcess emits readyRead() when data is
       
   484     available on the current read channel. It also emits
       
   485     readyReadStandardOutput() when new standard output data is
       
   486     available, and when new standard error data is available,
       
   487     readyReadStandardError() is emitted. Instead of calling read(),
       
   488     readLine(), or getChar(), you can explicitly read all data from
       
   489     either of the two channels by calling readAllStandardOutput() or
       
   490     readAllStandardError().
       
   491 
       
   492     The terminology for the channels can be misleading. Be aware that
       
   493     the process's output channels correspond to QProcess's
       
   494     \e read channels, whereas the process's input channels correspond
       
   495     to QProcess's \e write channels. This is because what we read
       
   496     using QProcess is the process's output, and what we write becomes
       
   497     the process's input.
       
   498 
       
   499     QProcess can merge the two output channels, so that standard
       
   500     output and standard error data from the running process both use
       
   501     the standard output channel. Call setProcessChannelMode() with
       
   502     MergedChannels before starting the process to activative
       
   503     this feature. You also have the option of forwarding the output of
       
   504     the running process to the calling, main process, by passing
       
   505     ForwardedChannels as the argument.
       
   506 
       
   507     Certain processes need special environment settings in order to
       
   508     operate. You can set environment variables for your process by
       
   509     calling setEnvironment(). To set a working directory, call
       
   510     setWorkingDirectory(). By default, processes are run in the
       
   511     current working directory of the calling process.
       
   512 
       
   513     \note On Symbian, setting environment or working directory
       
   514     is not supported. The working directory will always be the private
       
   515     directory of the running process.
       
   516 
       
   517     \section1 Synchronous Process API
       
   518 
       
   519     QProcess provides a set of functions which allow it to be used
       
   520     without an event loop, by suspending the calling thread until
       
   521     certain signals are emitted:
       
   522 
       
   523     \list
       
   524     \o waitForStarted() blocks until the process has started.
       
   525 
       
   526     \o waitForReadyRead() blocks until new data is
       
   527     available for reading on the current read channel.
       
   528 
       
   529     \o waitForBytesWritten() blocks until one payload of
       
   530     data has been written to the process.
       
   531 
       
   532     \o waitForFinished() blocks until the process has finished.
       
   533     \endlist
       
   534 
       
   535     Calling these functions from the main thread (the thread that
       
   536     calls QApplication::exec()) may cause your user interface to
       
   537     freeze.
       
   538 
       
   539     The following example runs \c gzip to compress the string "Qt
       
   540     rocks!", without an event loop:
       
   541 
       
   542     \snippet doc/src/snippets/process/process.cpp 0
       
   543 
       
   544     \section1 Notes for Windows Users
       
   545 
       
   546     Some Windows commands (for example, \c dir) are not provided by
       
   547     separate applications, but by the command interpreter itself.
       
   548     If you attempt to use QProcess to execute these commands directly,
       
   549     it won't work. One possible solution is to execute the command
       
   550     interpreter itself (\c{cmd.exe} on some Windows systems), and ask
       
   551     the interpreter to execute the desired command.
       
   552 
       
   553     \sa QBuffer, QFile, QTcpSocket
       
   554 */
       
   555 
       
   556 /*!
       
   557     \enum QProcess::ProcessChannel
       
   558 
       
   559     This enum describes the process channels used by the running process.
       
   560     Pass one of these values to setReadChannel() to set the
       
   561     current read channel of QProcess.
       
   562 
       
   563     \value StandardOutput The standard output (stdout) of the running
       
   564            process.
       
   565 
       
   566     \value StandardError The standard error (stderr) of the running
       
   567            process.
       
   568 
       
   569     \sa setReadChannel()
       
   570 */
       
   571 
       
   572 /*!
       
   573     \enum QProcess::ProcessChannelMode
       
   574 
       
   575     This enum describes the process channel modes of QProcess. Pass
       
   576     one of these values to setProcessChannelMode() to set the
       
   577     current read channel mode.
       
   578 
       
   579     \value SeparateChannels QProcess manages the output of the
       
   580     running process, keeping standard output and standard error data
       
   581     in separate internal buffers. You can select the QProcess's
       
   582     current read channel by calling setReadChannel(). This is the
       
   583     default channel mode of QProcess.
       
   584 
       
   585     \value MergedChannels QProcess merges the output of the running
       
   586     process into the standard output channel (\c stdout). The
       
   587     standard error channel (\c stderr) will not receive any data. The
       
   588     standard output and standard error data of the running process
       
   589     are interleaved.
       
   590 
       
   591     \value ForwardedChannels QProcess forwards the output of the
       
   592     running process onto the main process. Anything the child process
       
   593     writes to its standard output and standard error will be written
       
   594     to the standard output and standard error of the main process.
       
   595 
       
   596     \sa setProcessChannelMode()
       
   597 */
       
   598 
       
   599 /*!
       
   600     \enum QProcess::ProcessError
       
   601 
       
   602     This enum describes the different types of errors that are
       
   603     reported by QProcess.
       
   604 
       
   605     \value FailedToStart The process failed to start. Either the
       
   606     invoked program is missing, or you may have insufficient
       
   607     permissions to invoke the program.
       
   608 
       
   609     \value Crashed The process crashed some time after starting
       
   610     successfully.
       
   611 
       
   612     \value Timedout The last waitFor...() function timed out. The
       
   613     state of QProcess is unchanged, and you can try calling
       
   614     waitFor...() again.
       
   615 
       
   616     \value WriteError An error occurred when attempting to write to the
       
   617     process. For example, the process may not be running, or it may
       
   618     have closed its input channel.
       
   619 
       
   620     \value ReadError An error occurred when attempting to read from
       
   621     the process. For example, the process may not be running.
       
   622 
       
   623     \value UnknownError An unknown error occurred. This is the default
       
   624     return value of error().
       
   625 
       
   626     \sa error()
       
   627 */
       
   628 
       
   629 /*!
       
   630     \enum QProcess::ProcessState
       
   631 
       
   632     This enum describes the different states of QProcess.
       
   633 
       
   634     \value NotRunning The process is not running.
       
   635 
       
   636     \value Starting The process is starting, but the program has not
       
   637     yet been invoked.
       
   638 
       
   639     \value Running The process is running and is ready for reading and
       
   640     writing.
       
   641 
       
   642     \sa state()
       
   643 */
       
   644 
       
   645 /*!
       
   646     \enum QProcess::ExitStatus
       
   647 
       
   648     This enum describes the different exit statuses of QProcess.
       
   649 
       
   650     \value NormalExit The process exited normally.
       
   651 
       
   652     \value CrashExit The process crashed.
       
   653 
       
   654     \sa exitStatus()
       
   655 */
       
   656 
       
   657 /*!
       
   658     \fn void QProcess::error(QProcess::ProcessError error)
       
   659 
       
   660     This signal is emitted when an error occurs with the process. The
       
   661     specified \a error describes the type of error that occurred.
       
   662 */
       
   663 
       
   664 /*!
       
   665     \fn void QProcess::started()
       
   666 
       
   667     This signal is emitted by QProcess when the process has started,
       
   668     and state() returns \l Running.
       
   669 */
       
   670 
       
   671 /*!
       
   672     \fn void QProcess::stateChanged(QProcess::ProcessState newState)
       
   673 
       
   674     This signal is emitted whenever the state of QProcess changes. The
       
   675     \a newState argument is the state QProcess changed to.
       
   676 */
       
   677 
       
   678 /*!
       
   679     \fn void QProcess::finished(int exitCode)
       
   680     \obsolete
       
   681     \overload
       
   682 
       
   683     Use finished(int exitCode, QProcess::ExitStatus status) instead.
       
   684 */
       
   685 
       
   686 /*!
       
   687     \fn void QProcess::finished(int exitCode, QProcess::ExitStatus exitStatus)
       
   688 
       
   689     This signal is emitted when the process finishes. \a exitCode is the exit
       
   690     code of the process, and \a exitStatus is the exit status.  After the
       
   691     process has finished, the buffers in QProcess are still intact. You can
       
   692     still read any data that the process may have written before it finished.
       
   693 
       
   694     \sa exitStatus()
       
   695 */
       
   696 
       
   697 /*!
       
   698     \fn void QProcess::readyReadStandardOutput()
       
   699 
       
   700     This signal is emitted when the process has made new data
       
   701     available through its standard output channel (\c stdout). It is
       
   702     emitted regardless of the current \l{readChannel()}{read channel}.
       
   703 
       
   704     \sa readAllStandardOutput(), readChannel()
       
   705 */
       
   706 
       
   707 /*!
       
   708     \fn void QProcess::readyReadStandardError()
       
   709 
       
   710     This signal is emitted when the process has made new data
       
   711     available through its standard error channel (\c stderr). It is
       
   712     emitted regardless of the current \l{readChannel()}{read
       
   713     channel}.
       
   714 
       
   715     \sa readAllStandardError(), readChannel()
       
   716 */
       
   717 
       
   718 /*! \internal
       
   719 */
       
   720 QProcessPrivate::QProcessPrivate()
       
   721 {
       
   722     processChannel = QProcess::StandardOutput;
       
   723     processChannelMode = QProcess::SeparateChannels;
       
   724     processError = QProcess::UnknownError;
       
   725     processState = QProcess::NotRunning;
       
   726     pid = 0;
       
   727     sequenceNumber = 0;
       
   728     exitCode = 0;
       
   729     exitStatus = QProcess::NormalExit;
       
   730     startupSocketNotifier = 0;
       
   731     deathNotifier = 0;
       
   732     notifier = 0;
       
   733     pipeWriter = 0;
       
   734     childStartedPipe[0] = INVALID_Q_PIPE;
       
   735     childStartedPipe[1] = INVALID_Q_PIPE;
       
   736     deathPipe[0] = INVALID_Q_PIPE;
       
   737     deathPipe[1] = INVALID_Q_PIPE;
       
   738     exitCode = 0;
       
   739     crashed = false;
       
   740     dying = false;
       
   741     emittedReadyRead = false;
       
   742     emittedBytesWritten = false;
       
   743 #ifdef Q_WS_WIN
       
   744     pipeWriter = 0;
       
   745     processFinishedNotifier = 0;
       
   746 #endif // Q_WS_WIN
       
   747 #ifdef Q_OS_UNIX
       
   748     serial = 0;
       
   749 #endif
       
   750 #ifdef Q_OS_SYMBIAN
       
   751     symbianProcess = NULL;
       
   752     processLaunched = false;
       
   753 #endif
       
   754 }
       
   755 
       
   756 /*! \internal
       
   757 */
       
   758 QProcessPrivate::~QProcessPrivate()
       
   759 {
       
   760     if (stdinChannel.process)
       
   761         stdinChannel.process->stdoutChannel.clear();
       
   762     if (stdoutChannel.process)
       
   763         stdoutChannel.process->stdinChannel.clear();
       
   764 }
       
   765 
       
   766 /*! \internal
       
   767 */
       
   768 void QProcessPrivate::cleanup()
       
   769 {
       
   770     q_func()->setProcessState(QProcess::NotRunning);
       
   771 #ifdef Q_OS_WIN
       
   772     if (pid) {
       
   773         CloseHandle(pid->hThread);
       
   774         CloseHandle(pid->hProcess);
       
   775         delete pid;
       
   776         pid = 0;
       
   777     }
       
   778     if (processFinishedNotifier) {
       
   779         processFinishedNotifier->setEnabled(false);
       
   780         qDeleteInEventHandler(processFinishedNotifier);
       
   781         processFinishedNotifier = 0;
       
   782     }
       
   783 
       
   784 #endif
       
   785     pid = 0;
       
   786     sequenceNumber = 0;
       
   787     dying = false;
       
   788 
       
   789     if (stdoutChannel.notifier) {
       
   790         stdoutChannel.notifier->setEnabled(false);
       
   791         qDeleteInEventHandler(stdoutChannel.notifier);
       
   792         stdoutChannel.notifier = 0;
       
   793     }
       
   794     if (stderrChannel.notifier) {
       
   795         stderrChannel.notifier->setEnabled(false);
       
   796         qDeleteInEventHandler(stderrChannel.notifier);
       
   797         stderrChannel.notifier = 0;
       
   798     }
       
   799     if (stdinChannel.notifier) {
       
   800         stdinChannel.notifier->setEnabled(false);
       
   801         qDeleteInEventHandler(stdinChannel.notifier);
       
   802         stdinChannel.notifier = 0;
       
   803     }
       
   804     if (startupSocketNotifier) {
       
   805         startupSocketNotifier->setEnabled(false);
       
   806         qDeleteInEventHandler(startupSocketNotifier);
       
   807         startupSocketNotifier = 0;
       
   808     }
       
   809     if (deathNotifier) {
       
   810         deathNotifier->setEnabled(false);
       
   811         qDeleteInEventHandler(deathNotifier);
       
   812         deathNotifier = 0;
       
   813     }
       
   814     if (notifier) {
       
   815         qDeleteInEventHandler(notifier);
       
   816         notifier = 0;
       
   817     }
       
   818     destroyPipe(stdoutChannel.pipe);
       
   819     destroyPipe(stderrChannel.pipe);
       
   820     destroyPipe(stdinChannel.pipe);
       
   821     destroyPipe(childStartedPipe);
       
   822     destroyPipe(deathPipe);
       
   823 #ifdef Q_OS_UNIX
       
   824     serial = 0;
       
   825 #endif
       
   826 #ifdef Q_OS_SYMBIAN
       
   827     if (symbianProcess) {
       
   828         symbianProcess->Close();
       
   829         delete symbianProcess;
       
   830         symbianProcess = NULL;
       
   831     }
       
   832 #endif
       
   833 }
       
   834 
       
   835 /*! \internal
       
   836 */
       
   837 bool QProcessPrivate::_q_canReadStandardOutput()
       
   838 {
       
   839     Q_Q(QProcess);
       
   840     qint64 available = bytesAvailableFromStdout();
       
   841     if (available == 0) {
       
   842         if (stdoutChannel.notifier)
       
   843             stdoutChannel.notifier->setEnabled(false);
       
   844         destroyPipe(stdoutChannel.pipe);
       
   845 #if defined QPROCESS_DEBUG
       
   846         qDebug("QProcessPrivate::canReadStandardOutput(), 0 bytes available");
       
   847 #endif
       
   848         return false;
       
   849     }
       
   850 
       
   851     char *ptr = outputReadBuffer.reserve(available);
       
   852     qint64 readBytes = readFromStdout(ptr, available);
       
   853     if (readBytes == -1) {
       
   854         processError = QProcess::ReadError;
       
   855         q->setErrorString(QProcess::tr("Error reading from process"));
       
   856         emit q->error(processError);
       
   857 #if defined QPROCESS_DEBUG
       
   858         qDebug("QProcessPrivate::canReadStandardOutput(), failed to read from the process");
       
   859 #endif
       
   860         return false;
       
   861     }
       
   862 #if defined QPROCESS_DEBUG
       
   863     qDebug("QProcessPrivate::canReadStandardOutput(), read %d bytes from the process' output",
       
   864             int(readBytes));
       
   865 #endif
       
   866 
       
   867     if (stdoutChannel.closed) {
       
   868         outputReadBuffer.chop(readBytes);
       
   869         return false;
       
   870     }
       
   871 
       
   872     outputReadBuffer.chop(available - readBytes);
       
   873 
       
   874     bool didRead = false;
       
   875     if (readBytes == 0) {
       
   876         if (stdoutChannel.notifier)
       
   877             stdoutChannel.notifier->setEnabled(false);
       
   878     } else if (processChannel == QProcess::StandardOutput) {
       
   879         didRead = true;
       
   880         if (!emittedReadyRead) {
       
   881             emittedReadyRead = true;
       
   882             emit q->readyRead();
       
   883             emittedReadyRead = false;
       
   884         }
       
   885     }
       
   886     emit q->readyReadStandardOutput();
       
   887     return didRead;
       
   888 }
       
   889 
       
   890 /*! \internal
       
   891 */
       
   892 bool QProcessPrivate::_q_canReadStandardError()
       
   893 {
       
   894     Q_Q(QProcess);
       
   895     qint64 available = bytesAvailableFromStderr();
       
   896     if (available == 0) {
       
   897         if (stderrChannel.notifier)
       
   898             stderrChannel.notifier->setEnabled(false);
       
   899         destroyPipe(stderrChannel.pipe);
       
   900         return false;
       
   901     }
       
   902 
       
   903     char *ptr = errorReadBuffer.reserve(available);
       
   904     qint64 readBytes = readFromStderr(ptr, available);
       
   905     if (readBytes == -1) {
       
   906         processError = QProcess::ReadError;
       
   907         q->setErrorString(QProcess::tr("Error reading from process"));
       
   908         emit q->error(processError);
       
   909         return false;
       
   910     }
       
   911     if (stderrChannel.closed) {
       
   912         errorReadBuffer.chop(readBytes);
       
   913         return false;
       
   914     }
       
   915 
       
   916     errorReadBuffer.chop(available - readBytes);
       
   917 
       
   918     bool didRead = false;
       
   919     if (readBytes == 0) {
       
   920         if (stderrChannel.notifier)
       
   921             stderrChannel.notifier->setEnabled(false);
       
   922     } else if (processChannel == QProcess::StandardError) {
       
   923         didRead = true;
       
   924         if (!emittedReadyRead) {
       
   925             emittedReadyRead = true;
       
   926             emit q->readyRead();
       
   927             emittedReadyRead = false;
       
   928         }
       
   929     }
       
   930     emit q->readyReadStandardError();
       
   931     return didRead;
       
   932 }
       
   933 
       
   934 /*! \internal
       
   935 */
       
   936 bool QProcessPrivate::_q_canWrite()
       
   937 {
       
   938     Q_Q(QProcess);
       
   939     if (stdinChannel.notifier)
       
   940         stdinChannel.notifier->setEnabled(false);
       
   941 
       
   942     if (writeBuffer.isEmpty()) {
       
   943 #if defined QPROCESS_DEBUG
       
   944         qDebug("QProcessPrivate::canWrite(), not writing anything (empty write buffer).");
       
   945 #endif
       
   946         return false;
       
   947     }
       
   948 
       
   949     qint64 written = writeToStdin(writeBuffer.readPointer(),
       
   950                                       writeBuffer.nextDataBlockSize());
       
   951     if (written < 0) {
       
   952         destroyPipe(stdinChannel.pipe);
       
   953         processError = QProcess::WriteError;
       
   954         q->setErrorString(QProcess::tr("Error writing to process"));
       
   955 #if defined(QPROCESS_DEBUG) && !defined(Q_OS_WINCE)
       
   956         qDebug("QProcessPrivate::canWrite(), failed to write (%s)", strerror(errno));
       
   957 #endif
       
   958         emit q->error(processError);
       
   959         return false;
       
   960     }
       
   961 
       
   962 #if defined QPROCESS_DEBUG
       
   963     qDebug("QProcessPrivate::canWrite(), wrote %d bytes to the process input", int(written));
       
   964 #endif
       
   965 
       
   966     writeBuffer.free(written);
       
   967     if (!emittedBytesWritten) {
       
   968         emittedBytesWritten = true;
       
   969         emit q->bytesWritten(written);
       
   970         emittedBytesWritten = false;
       
   971     }
       
   972     if (stdinChannel.notifier && !writeBuffer.isEmpty())
       
   973         stdinChannel.notifier->setEnabled(true);
       
   974     if (writeBuffer.isEmpty() && stdinChannel.closed)
       
   975         closeWriteChannel();
       
   976     return true;
       
   977 }
       
   978 
       
   979 /*! \internal
       
   980 */
       
   981 bool QProcessPrivate::_q_processDied()
       
   982 {
       
   983     Q_Q(QProcess);
       
   984 #if defined QPROCESS_DEBUG
       
   985     qDebug("QProcessPrivate::_q_processDied()");
       
   986 #endif
       
   987 #ifdef Q_OS_UNIX
       
   988     if (!waitForDeadChild())
       
   989         return false;
       
   990 #endif
       
   991 #ifdef Q_OS_WIN
       
   992     if (processFinishedNotifier)
       
   993         processFinishedNotifier->setEnabled(false);
       
   994 #endif
       
   995 
       
   996     // the process may have died before it got a chance to report that it was
       
   997     // either running or stopped, so we will call _q_startupNotification() and
       
   998     // give it a chance to emit started() or error(FailedToStart).
       
   999     if (processState == QProcess::Starting) {
       
  1000         if (!_q_startupNotification())
       
  1001             return true;
       
  1002     }
       
  1003 
       
  1004     if (dying) {
       
  1005         // at this point we know the process is dead. prevent
       
  1006         // reentering this slot recursively by calling waitForFinished()
       
  1007         // or opening a dialog inside slots connected to the readyRead
       
  1008         // signals emitted below.
       
  1009         return true;
       
  1010     }
       
  1011     dying = true;
       
  1012 
       
  1013     // in case there is data in the pipe line and this slot by chance
       
  1014     // got called before the read notifications, call these two slots
       
  1015     // so the data is made available before the process dies.
       
  1016     _q_canReadStandardOutput();
       
  1017     _q_canReadStandardError();
       
  1018 
       
  1019     findExitCode();
       
  1020 
       
  1021     if (crashed) {
       
  1022         exitStatus = QProcess::CrashExit;
       
  1023         processError = QProcess::Crashed;
       
  1024         q->setErrorString(QProcess::tr("Process crashed"));
       
  1025         emit q->error(processError);
       
  1026     }
       
  1027 
       
  1028     bool wasRunning = (processState == QProcess::Running);
       
  1029 
       
  1030     cleanup();
       
  1031 
       
  1032     if (wasRunning) {
       
  1033         // we received EOF now:
       
  1034         emit q->readChannelFinished();
       
  1035         // in the future:
       
  1036         //emit q->standardOutputClosed();
       
  1037         //emit q->standardErrorClosed();
       
  1038 
       
  1039         emit q->finished(exitCode);
       
  1040         emit q->finished(exitCode, exitStatus);
       
  1041     }
       
  1042 #if defined QPROCESS_DEBUG
       
  1043     qDebug("QProcessPrivate::_q_processDied() process is dead");
       
  1044 #endif
       
  1045     return true;
       
  1046 }
       
  1047 
       
  1048 /*! \internal
       
  1049 */
       
  1050 bool QProcessPrivate::_q_startupNotification()
       
  1051 {
       
  1052     Q_Q(QProcess);
       
  1053 #if defined QPROCESS_DEBUG
       
  1054     qDebug("QProcessPrivate::startupNotification()");
       
  1055 #endif
       
  1056 
       
  1057     if (startupSocketNotifier)
       
  1058         startupSocketNotifier->setEnabled(false);
       
  1059     if (processStarted()) {
       
  1060         q->setProcessState(QProcess::Running);
       
  1061         emit q->started();
       
  1062         return true;
       
  1063     }
       
  1064 
       
  1065     q->setProcessState(QProcess::NotRunning);
       
  1066     processError = QProcess::FailedToStart;
       
  1067     emit q->error(processError);
       
  1068 #ifdef Q_OS_UNIX
       
  1069     // make sure the process manager removes this entry
       
  1070     waitForDeadChild();
       
  1071     findExitCode();
       
  1072 #endif
       
  1073     cleanup();
       
  1074     return false;
       
  1075 }
       
  1076 
       
  1077 /*! \internal
       
  1078 */
       
  1079 void QProcessPrivate::closeWriteChannel()
       
  1080 {
       
  1081 #if defined QPROCESS_DEBUG
       
  1082     qDebug("QProcessPrivate::closeWriteChannel()");
       
  1083 #endif
       
  1084     if (stdinChannel.notifier) {
       
  1085         extern void qDeleteInEventHandler(QObject *o);
       
  1086         stdinChannel.notifier->setEnabled(false);
       
  1087         if (stdinChannel.notifier) {
       
  1088             qDeleteInEventHandler(stdinChannel.notifier);
       
  1089             stdinChannel.notifier = 0;
       
  1090         }
       
  1091     }
       
  1092 #ifdef Q_OS_WIN
       
  1093     // ### Find a better fix, feeding the process little by little
       
  1094     // instead.
       
  1095     flushPipeWriter();
       
  1096 #endif
       
  1097     destroyPipe(stdinChannel.pipe);
       
  1098 }
       
  1099 
       
  1100 /*!
       
  1101     Constructs a QProcess object with the given \a parent.
       
  1102 */
       
  1103 QProcess::QProcess(QObject *parent)
       
  1104     : QIODevice(*new QProcessPrivate, parent)
       
  1105 {
       
  1106 #if defined QPROCESS_DEBUG
       
  1107     qDebug("QProcess::QProcess(%p)", parent);
       
  1108 #endif
       
  1109 }
       
  1110 
       
  1111 /*!
       
  1112     Destructs the QProcess object, i.e., killing the process.
       
  1113 
       
  1114     Note that this function will not return until the process is
       
  1115     terminated.
       
  1116 */
       
  1117 QProcess::~QProcess()
       
  1118 {
       
  1119     Q_D(QProcess);
       
  1120     if (d->processState != NotRunning) {
       
  1121         qWarning("QProcess: Destroyed while process is still running.");
       
  1122         kill();
       
  1123         waitForFinished();
       
  1124     }
       
  1125 #ifdef Q_OS_UNIX
       
  1126     // make sure the process manager removes this entry
       
  1127     d->findExitCode();
       
  1128 #endif
       
  1129     d->cleanup();
       
  1130 }
       
  1131 
       
  1132 /*!
       
  1133     \obsolete
       
  1134     Returns the read channel mode of the QProcess. This function is
       
  1135     equivalent to processChannelMode()
       
  1136 
       
  1137     \sa processChannelMode()
       
  1138 */
       
  1139 QProcess::ProcessChannelMode QProcess::readChannelMode() const
       
  1140 {
       
  1141     return processChannelMode();
       
  1142 }
       
  1143 
       
  1144 /*!
       
  1145     \obsolete
       
  1146 
       
  1147     Use setProcessChannelMode(\a mode) instead.
       
  1148 
       
  1149     \sa setProcessChannelMode()
       
  1150 */
       
  1151 void QProcess::setReadChannelMode(ProcessChannelMode mode)
       
  1152 {
       
  1153     setProcessChannelMode(mode);
       
  1154 }
       
  1155 
       
  1156 /*!
       
  1157     \since 4.2
       
  1158 
       
  1159     Returns the channel mode of the QProcess standard output and
       
  1160     standard error channels.
       
  1161 
       
  1162     \sa setProcessChannelMode(), ProcessChannelMode, setReadChannel()
       
  1163 */
       
  1164 QProcess::ProcessChannelMode QProcess::processChannelMode() const
       
  1165 {
       
  1166     Q_D(const QProcess);
       
  1167     return d->processChannelMode;
       
  1168 }
       
  1169 
       
  1170 /*!
       
  1171     \since 4.2
       
  1172 
       
  1173     Sets the channel mode of the QProcess standard output and standard
       
  1174     error channels to the \a mode specified.
       
  1175     This mode will be used the next time start() is called. For example:
       
  1176 
       
  1177     \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 0
       
  1178 
       
  1179     \sa processChannelMode(), ProcessChannelMode, setReadChannel()
       
  1180 */
       
  1181 void QProcess::setProcessChannelMode(ProcessChannelMode mode)
       
  1182 {
       
  1183     Q_D(QProcess);
       
  1184     d->processChannelMode = mode;
       
  1185 }
       
  1186 
       
  1187 /*!
       
  1188     Returns the current read channel of the QProcess.
       
  1189 
       
  1190     \sa setReadChannel()
       
  1191 */
       
  1192 QProcess::ProcessChannel QProcess::readChannel() const
       
  1193 {
       
  1194     Q_D(const QProcess);
       
  1195     return d->processChannel;
       
  1196 }
       
  1197 
       
  1198 /*!
       
  1199     Sets the current read channel of the QProcess to the given \a
       
  1200     channel. The current input channel is used by the functions
       
  1201     read(), readAll(), readLine(), and getChar(). It also determines
       
  1202     which channel triggers QProcess to emit readyRead().
       
  1203 
       
  1204     \sa readChannel()
       
  1205 */
       
  1206 void QProcess::setReadChannel(ProcessChannel channel)
       
  1207 {
       
  1208     Q_D(QProcess);
       
  1209     if (d->processChannel != channel) {
       
  1210         QByteArray buf = d->buffer.readAll();
       
  1211         if (d->processChannel == QProcess::StandardOutput) {
       
  1212             for (int i = buf.size() - 1; i >= 0; --i)
       
  1213                 d->outputReadBuffer.ungetChar(buf.at(i));
       
  1214         } else {
       
  1215             for (int i = buf.size() - 1; i >= 0; --i)
       
  1216                 d->errorReadBuffer.ungetChar(buf.at(i));
       
  1217         }
       
  1218     }
       
  1219     d->processChannel = channel;
       
  1220 }
       
  1221 
       
  1222 /*!
       
  1223     Closes the read channel \a channel. After calling this function,
       
  1224     QProcess will no longer receive data on the channel. Any data that
       
  1225     has already been received is still available for reading.
       
  1226 
       
  1227     Call this function to save memory, if you are not interested in
       
  1228     the output of the process.
       
  1229 
       
  1230     \sa closeWriteChannel(), setReadChannel()
       
  1231 */
       
  1232 void QProcess::closeReadChannel(ProcessChannel channel)
       
  1233 {
       
  1234     Q_D(QProcess);
       
  1235 
       
  1236     if (channel == StandardOutput)
       
  1237         d->stdoutChannel.closed = true;
       
  1238     else
       
  1239         d->stderrChannel.closed = true;
       
  1240 }
       
  1241 
       
  1242 /*!
       
  1243     Schedules the write channel of QProcess to be closed. The channel
       
  1244     will close once all data has been written to the process. After
       
  1245     calling this function, any attempts to write to the process will
       
  1246     fail.
       
  1247 
       
  1248     Closing the write channel is necessary for programs that read
       
  1249     input data until the channel has been closed. For example, the
       
  1250     program "more" is used to display text data in a console on both
       
  1251     Unix and Windows. But it will not display the text data until
       
  1252     QProcess's write channel has been closed. Example:
       
  1253 
       
  1254     \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 1
       
  1255 
       
  1256     The write channel is implicitly opened when start() is called.
       
  1257 
       
  1258     \sa closeReadChannel()
       
  1259 */
       
  1260 void QProcess::closeWriteChannel()
       
  1261 {
       
  1262     Q_D(QProcess);
       
  1263     d->stdinChannel.closed = true; // closing
       
  1264     if (d->writeBuffer.isEmpty())
       
  1265         d->closeWriteChannel();
       
  1266 }
       
  1267 
       
  1268 /*!
       
  1269     \since 4.2
       
  1270 
       
  1271     Redirects the process' standard input to the file indicated by \a
       
  1272     fileName. When an input redirection is in place, the QProcess
       
  1273     object will be in read-only mode (calling write() will result in
       
  1274     error).
       
  1275 
       
  1276     If the file \a fileName does not exist at the moment start() is
       
  1277     called or is not readable, starting the process will fail.
       
  1278 
       
  1279     Calling setStandardInputFile() after the process has started has no
       
  1280     effect.
       
  1281 
       
  1282     \sa setStandardOutputFile(), setStandardErrorFile(),
       
  1283         setStandardOutputProcess()
       
  1284 */
       
  1285 void QProcess::setStandardInputFile(const QString &fileName)
       
  1286 {
       
  1287     Q_D(QProcess);
       
  1288     d->stdinChannel = fileName;
       
  1289 }
       
  1290 
       
  1291 /*!
       
  1292     \since 4.2
       
  1293 
       
  1294     Redirects the process' standard output to the file \a
       
  1295     fileName. When the redirection is in place, the standard output
       
  1296     read channel is closed: reading from it using read() will always
       
  1297     fail, as will readAllStandardOutput().
       
  1298 
       
  1299     If the file \a fileName doesn't exist at the moment start() is
       
  1300     called, it will be created. If it cannot be created, the starting
       
  1301     will fail.
       
  1302 
       
  1303     If the file exists and \a mode is QIODevice::Truncate, the file
       
  1304     will be truncated. Otherwise (if \a mode is QIODevice::Append),
       
  1305     the file will be appended to.
       
  1306 
       
  1307     Calling setStandardOutputFile() after the process has started has
       
  1308     no effect.
       
  1309 
       
  1310     \sa setStandardInputFile(), setStandardErrorFile(),
       
  1311         setStandardOutputProcess()
       
  1312 */
       
  1313 void QProcess::setStandardOutputFile(const QString &fileName, OpenMode mode)
       
  1314 {
       
  1315     Q_ASSERT(mode == Append || mode == Truncate);
       
  1316     Q_D(QProcess);
       
  1317 
       
  1318     d->stdoutChannel = fileName;
       
  1319     d->stdoutChannel.append = mode == Append;
       
  1320 }
       
  1321 
       
  1322 /*!
       
  1323     \since 4.2
       
  1324 
       
  1325     Redirects the process' standard error to the file \a
       
  1326     fileName. When the redirection is in place, the standard error
       
  1327     read channel is closed: reading from it using read() will always
       
  1328     fail, as will readAllStandardError(). The file will be appended to
       
  1329     if \a mode is Append, otherwise, it will be truncated.
       
  1330 
       
  1331     See setStandardOutputFile() for more information on how the file
       
  1332     is opened.
       
  1333 
       
  1334     Note: if setProcessChannelMode() was called with an argument of
       
  1335     QProcess::MergedChannels, this function has no effect.
       
  1336 
       
  1337     \sa setStandardInputFile(), setStandardOutputFile(),
       
  1338         setStandardOutputProcess()
       
  1339 */
       
  1340 void QProcess::setStandardErrorFile(const QString &fileName, OpenMode mode)
       
  1341 {
       
  1342     Q_ASSERT(mode == Append || mode == Truncate);
       
  1343     Q_D(QProcess);
       
  1344 
       
  1345     d->stderrChannel = fileName;
       
  1346     d->stderrChannel.append = mode == Append;
       
  1347 }
       
  1348 
       
  1349 /*!
       
  1350     \since 4.2
       
  1351 
       
  1352     Pipes the standard output stream of this process to the \a
       
  1353     destination process' standard input.
       
  1354 
       
  1355     The following shell command:
       
  1356     \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 2
       
  1357 
       
  1358     Can be accomplished with QProcesses with the following code:
       
  1359     \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 3
       
  1360 */
       
  1361 void QProcess::setStandardOutputProcess(QProcess *destination)
       
  1362 {
       
  1363     QProcessPrivate *dfrom = d_func();
       
  1364     QProcessPrivate *dto = destination->d_func();
       
  1365     dfrom->stdoutChannel.pipeTo(dto);
       
  1366     dto->stdinChannel.pipeFrom(dfrom);
       
  1367 }
       
  1368 
       
  1369 /*!
       
  1370     If QProcess has been assigned a working directory, this function returns
       
  1371     the working directory that the QProcess will enter before the program has
       
  1372     started. Otherwise, (i.e., no directory has been assigned,) an empty
       
  1373     string is returned, and QProcess will use the application's current
       
  1374     working directory instead.
       
  1375 
       
  1376     \sa setWorkingDirectory()
       
  1377 */
       
  1378 QString QProcess::workingDirectory() const
       
  1379 {
       
  1380     Q_D(const QProcess);
       
  1381     return d->workingDirectory;
       
  1382 }
       
  1383 
       
  1384 /*!
       
  1385     Sets the working directory to \a dir. QProcess will start the
       
  1386     process in this directory. The default behavior is to start the
       
  1387     process in the working directory of the calling process.
       
  1388 
       
  1389     \note The working directory setting is ignored on Symbian;
       
  1390     the private directory of the process is considered its working
       
  1391     directory.
       
  1392 
       
  1393     \sa workingDirectory(), start()
       
  1394 */
       
  1395 void QProcess::setWorkingDirectory(const QString &dir)
       
  1396 {
       
  1397     Q_D(QProcess);
       
  1398     d->workingDirectory = dir;
       
  1399 }
       
  1400 
       
  1401 /*!
       
  1402     Returns the native process identifier for the running process, if
       
  1403     available.  If no process is currently running, 0 is returned.
       
  1404 */
       
  1405 Q_PID QProcess::pid() const
       
  1406 {
       
  1407     Q_D(const QProcess);
       
  1408     return d->pid;
       
  1409 }
       
  1410 
       
  1411 /*! \reimp
       
  1412 
       
  1413     This function operates on the current read channel.
       
  1414 
       
  1415     \sa readChannel(), setReadChannel()
       
  1416 */
       
  1417 bool QProcess::canReadLine() const
       
  1418 {
       
  1419     Q_D(const QProcess);
       
  1420     const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
       
  1421                                     ? &d->errorReadBuffer
       
  1422                                     : &d->outputReadBuffer;
       
  1423     return readBuffer->canReadLine() || QIODevice::canReadLine();
       
  1424 }
       
  1425 
       
  1426 /*!
       
  1427     Closes all communication with the process and kills it. After calling this
       
  1428     function, QProcess will no longer emit readyRead(), and data can no
       
  1429     longer be read or written.
       
  1430 */
       
  1431 void QProcess::close()
       
  1432 {
       
  1433     emit aboutToClose();
       
  1434     while (waitForBytesWritten(-1))
       
  1435         ;
       
  1436     kill();
       
  1437     waitForFinished(-1);
       
  1438     QIODevice::close();
       
  1439 }
       
  1440 
       
  1441 /*! \reimp
       
  1442 
       
  1443    Returns true if the process is not running, and no more data is available
       
  1444    for reading; otherwise returns false.
       
  1445 */
       
  1446 bool QProcess::atEnd() const
       
  1447 {
       
  1448     Q_D(const QProcess);
       
  1449     const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
       
  1450                                     ? &d->errorReadBuffer
       
  1451                                     : &d->outputReadBuffer;
       
  1452     return QIODevice::atEnd() && (!isOpen() || readBuffer->isEmpty());
       
  1453 }
       
  1454 
       
  1455 /*! \reimp
       
  1456 */
       
  1457 bool QProcess::isSequential() const
       
  1458 {
       
  1459     return true;
       
  1460 }
       
  1461 
       
  1462 /*! \reimp
       
  1463 */
       
  1464 qint64 QProcess::bytesAvailable() const
       
  1465 {
       
  1466     Q_D(const QProcess);
       
  1467     const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
       
  1468                                     ? &d->errorReadBuffer
       
  1469                                     : &d->outputReadBuffer;
       
  1470 #if defined QPROCESS_DEBUG
       
  1471     qDebug("QProcess::bytesAvailable() == %i (%s)", readBuffer->size(),
       
  1472            (d->processChannel == QProcess::StandardError) ? "stderr" : "stdout");
       
  1473 #endif
       
  1474     return readBuffer->size() + QIODevice::bytesAvailable();
       
  1475 }
       
  1476 
       
  1477 /*! \reimp
       
  1478 */
       
  1479 qint64 QProcess::bytesToWrite() const
       
  1480 {
       
  1481     Q_D(const QProcess);
       
  1482     qint64 size = d->writeBuffer.size();
       
  1483 #ifdef Q_OS_WIN
       
  1484     size += d->pipeWriterBytesToWrite();
       
  1485 #endif
       
  1486     return size;
       
  1487 }
       
  1488 
       
  1489 /*!
       
  1490     Returns the type of error that occurred last.
       
  1491 
       
  1492     \sa state()
       
  1493 */
       
  1494 QProcess::ProcessError QProcess::error() const
       
  1495 {
       
  1496     Q_D(const QProcess);
       
  1497     return d->processError;
       
  1498 }
       
  1499 
       
  1500 /*!
       
  1501     Returns the current state of the process.
       
  1502 
       
  1503     \sa stateChanged(), error()
       
  1504 */
       
  1505 QProcess::ProcessState QProcess::state() const
       
  1506 {
       
  1507     Q_D(const QProcess);
       
  1508     return d->processState;
       
  1509 }
       
  1510 
       
  1511 /*!
       
  1512     \deprecated
       
  1513     Sets the environment that QProcess will use when starting a process to the
       
  1514     \a environment specified which consists of a list of key=value pairs.
       
  1515 
       
  1516     For example, the following code adds the \c{C:\\BIN} directory to the list of
       
  1517     executable paths (\c{PATHS}) on Windows:
       
  1518 
       
  1519     \snippet doc/src/snippets/qprocess-environment/main.cpp 0
       
  1520 
       
  1521     \note This function is less efficient than the setProcessEnvironment()
       
  1522     function.
       
  1523 
       
  1524     \sa environment(), setProcessEnvironment(), systemEnvironment()
       
  1525 */
       
  1526 void QProcess::setEnvironment(const QStringList &environment)
       
  1527 {
       
  1528     setProcessEnvironment(QProcessEnvironmentPrivate::fromList(environment));
       
  1529 }
       
  1530 
       
  1531 /*!
       
  1532     \deprecated
       
  1533     Returns the environment that QProcess will use when starting a
       
  1534     process, or an empty QStringList if no environment has been set
       
  1535     using setEnvironment() or setEnvironmentHash(). If no environment
       
  1536     has been set, the environment of the calling process will be used.
       
  1537 
       
  1538     \note The environment settings are ignored on Windows CE and Symbian,
       
  1539     as there is no concept of an environment.
       
  1540 
       
  1541     \sa processEnvironment(), setEnvironment(), systemEnvironment()
       
  1542 */
       
  1543 QStringList QProcess::environment() const
       
  1544 {
       
  1545     Q_D(const QProcess);
       
  1546     return d->environment.toStringList();
       
  1547 }
       
  1548 
       
  1549 /*!
       
  1550     \since 4.6
       
  1551     Sets the environment that QProcess will use when starting a process to the
       
  1552     \a environment object.
       
  1553 
       
  1554     For example, the following code adds the \c{C:\\BIN} directory to the list of
       
  1555     executable paths (\c{PATHS}) on Windows and sets \c{TMPDIR}:
       
  1556 
       
  1557     \snippet doc/src/snippets/qprocess-environment/main.cpp 1
       
  1558 
       
  1559     Note how, on Windows, environment variable names are case-insensitive.
       
  1560 
       
  1561     \sa processEnvironment(), QProcessEnvironment::systemEnvironment(), setEnvironment()
       
  1562 */
       
  1563 void QProcess::setProcessEnvironment(const QProcessEnvironment &environment)
       
  1564 {
       
  1565     Q_D(QProcess);
       
  1566     d->environment = environment;
       
  1567 }
       
  1568 
       
  1569 /*!
       
  1570     \since 4.6
       
  1571     Returns the environment that QProcess will use when starting a
       
  1572     process, or an empty object if no environment has been set using
       
  1573     setEnvironment() or setProcessEnvironment(). If no environment has
       
  1574     been set, the environment of the calling process will be used.
       
  1575 
       
  1576     \note The environment settings are ignored on Windows CE,
       
  1577     as there is no concept of an environment.
       
  1578 
       
  1579     \sa setProcessEnvironment(), setEnvironment(), QProcessEnvironment::isEmpty()
       
  1580 */
       
  1581 QProcessEnvironment QProcess::processEnvironment() const
       
  1582 {
       
  1583     Q_D(const QProcess);
       
  1584     return d->environment;
       
  1585 }
       
  1586 
       
  1587 /*!
       
  1588     Blocks until the process has started and the started() signal has
       
  1589     been emitted, or until \a msecs milliseconds have passed.
       
  1590 
       
  1591     Returns true if the process was started successfully; otherwise
       
  1592     returns false (if the operation timed out or if an error
       
  1593     occurred).
       
  1594 
       
  1595     This function can operate without an event loop. It is
       
  1596     useful when writing non-GUI applications and when performing
       
  1597     I/O operations in a non-GUI thread.
       
  1598 
       
  1599     \warning Calling this function from the main (GUI) thread
       
  1600     might cause your user interface to freeze.
       
  1601 
       
  1602     If msecs is -1, this function will not time out.
       
  1603 
       
  1604     \sa started(), waitForReadyRead(), waitForBytesWritten(), waitForFinished()
       
  1605 */
       
  1606 bool QProcess::waitForStarted(int msecs)
       
  1607 {
       
  1608     Q_D(QProcess);
       
  1609     if (d->processState == QProcess::Starting) {
       
  1610         if (!d->waitForStarted(msecs))
       
  1611             return false;
       
  1612         setProcessState(QProcess::Running);
       
  1613         emit started();
       
  1614     }
       
  1615     return d->processState == QProcess::Running;
       
  1616 }
       
  1617 
       
  1618 /*! \reimp
       
  1619 */
       
  1620 bool QProcess::waitForReadyRead(int msecs)
       
  1621 {
       
  1622     Q_D(QProcess);
       
  1623 
       
  1624     if (d->processState == QProcess::NotRunning)
       
  1625         return false;
       
  1626     if (d->processChannel == QProcess::StandardOutput && d->stdoutChannel.closed)
       
  1627         return false;
       
  1628     if (d->processChannel == QProcess::StandardError && d->stderrChannel.closed)
       
  1629         return false;
       
  1630     return d->waitForReadyRead(msecs);
       
  1631 }
       
  1632 
       
  1633 /*! \reimp
       
  1634 */
       
  1635 bool QProcess::waitForBytesWritten(int msecs)
       
  1636 {
       
  1637     Q_D(QProcess);
       
  1638     if (d->processState == QProcess::NotRunning)
       
  1639         return false;
       
  1640     if (d->processState == QProcess::Starting) {
       
  1641         QTime stopWatch;
       
  1642         stopWatch.start();
       
  1643         bool started = waitForStarted(msecs);
       
  1644         if (!started)
       
  1645             return false;
       
  1646         if (msecs != -1)
       
  1647             msecs -= stopWatch.elapsed();
       
  1648     }
       
  1649 
       
  1650     return d->waitForBytesWritten(msecs);
       
  1651 }
       
  1652 
       
  1653 /*!
       
  1654     Blocks until the process has finished and the finished() signal
       
  1655     has been emitted, or until \a msecs milliseconds have passed.
       
  1656 
       
  1657     Returns true if the process finished; otherwise returns false (if
       
  1658     the operation timed out, if an error occurred, or if this QProcess
       
  1659     is already finished).
       
  1660 
       
  1661     This function can operate without an event loop. It is
       
  1662     useful when writing non-GUI applications and when performing
       
  1663     I/O operations in a non-GUI thread.
       
  1664 
       
  1665     \warning Calling this function from the main (GUI) thread
       
  1666     might cause your user interface to freeze.
       
  1667 
       
  1668     If msecs is -1, this function will not time out.
       
  1669 
       
  1670     \sa finished(), waitForStarted(), waitForReadyRead(), waitForBytesWritten()
       
  1671 */
       
  1672 bool QProcess::waitForFinished(int msecs)
       
  1673 {
       
  1674     Q_D(QProcess);
       
  1675     if (d->processState == QProcess::NotRunning)
       
  1676         return false;
       
  1677     if (d->processState == QProcess::Starting) {
       
  1678         QTime stopWatch;
       
  1679         stopWatch.start();
       
  1680         bool started = waitForStarted(msecs);
       
  1681         if (!started)
       
  1682             return false;
       
  1683         if (msecs != -1)
       
  1684             msecs -= stopWatch.elapsed();
       
  1685     }
       
  1686 
       
  1687     return d->waitForFinished(msecs);
       
  1688 }
       
  1689 
       
  1690 /*!
       
  1691     Sets the current state of the QProcess to the \a state specified.
       
  1692 
       
  1693     \sa state()
       
  1694 */
       
  1695 void QProcess::setProcessState(ProcessState state)
       
  1696 {
       
  1697     Q_D(QProcess);
       
  1698     if (d->processState == state)
       
  1699         return;
       
  1700     d->processState = state;
       
  1701     emit stateChanged(state);
       
  1702 }
       
  1703 
       
  1704 /*!
       
  1705   This function is called in the child process context just before the
       
  1706     program is executed on Unix or Mac OS X (i.e., after \e fork(), but before
       
  1707     \e execve()). Reimplement this function to do last minute initialization
       
  1708     of the child process. Example:
       
  1709 
       
  1710     \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 4
       
  1711 
       
  1712     You cannot exit the process (by calling exit(), for instance) from
       
  1713     this function. If you need to stop the program before it starts
       
  1714     execution, your workaround is to emit finished() and then call
       
  1715     exit().
       
  1716 
       
  1717     \warning This function is called by QProcess on Unix and Mac OS X
       
  1718     only. On Windows, it is not called.
       
  1719 */
       
  1720 void QProcess::setupChildProcess()
       
  1721 {
       
  1722 }
       
  1723 
       
  1724 /*! \reimp
       
  1725 */
       
  1726 qint64 QProcess::readData(char *data, qint64 maxlen)
       
  1727 {
       
  1728     Q_D(QProcess);
       
  1729     QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
       
  1730                               ? &d->errorReadBuffer
       
  1731                               : &d->outputReadBuffer;
       
  1732 
       
  1733     if (maxlen == 1 && !readBuffer->isEmpty()) {
       
  1734         int c = readBuffer->getChar();
       
  1735         if (c == -1) {
       
  1736 #if defined QPROCESS_DEBUG
       
  1737             qDebug("QProcess::readData(%p \"%s\", %d) == -1",
       
  1738                    data, qt_prettyDebug(data, 1, maxlen).constData(), 1);
       
  1739 #endif
       
  1740             return -1;
       
  1741         }
       
  1742         *data = (char) c;
       
  1743 #if defined QPROCESS_DEBUG
       
  1744         qDebug("QProcess::readData(%p \"%s\", %d) == 1",
       
  1745                data, qt_prettyDebug(data, 1, maxlen).constData(), 1);
       
  1746 #endif
       
  1747         return 1;
       
  1748     }
       
  1749 
       
  1750     qint64 bytesToRead = qint64(qMin(readBuffer->size(), (int)maxlen));
       
  1751     qint64 readSoFar = 0;
       
  1752     while (readSoFar < bytesToRead) {
       
  1753         const char *ptr = readBuffer->readPointer();
       
  1754         int bytesToReadFromThisBlock = qMin<qint64>(bytesToRead - readSoFar,
       
  1755                                             readBuffer->nextDataBlockSize());
       
  1756         memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
       
  1757         readSoFar += bytesToReadFromThisBlock;
       
  1758         readBuffer->free(bytesToReadFromThisBlock);
       
  1759     }
       
  1760 
       
  1761 #if defined QPROCESS_DEBUG
       
  1762     qDebug("QProcess::readData(%p \"%s\", %lld) == %lld",
       
  1763            data, qt_prettyDebug(data, readSoFar, 16).constData(), maxlen, readSoFar);
       
  1764 #endif
       
  1765     if (!readSoFar && d->processState == QProcess::NotRunning)
       
  1766         return -1;              // EOF
       
  1767     return readSoFar;
       
  1768 }
       
  1769 
       
  1770 /*! \reimp
       
  1771 */
       
  1772 qint64 QProcess::writeData(const char *data, qint64 len)
       
  1773 {
       
  1774     Q_D(QProcess);
       
  1775 
       
  1776 #if defined(Q_OS_WINCE)
       
  1777     Q_UNUSED(data);
       
  1778     Q_UNUSED(len);
       
  1779     d->processError = QProcess::WriteError;
       
  1780     setErrorString(tr("Error writing to process"));
       
  1781     emit error(d->processError);
       
  1782     return -1;
       
  1783 #endif
       
  1784 
       
  1785     if (d->stdinChannel.closed) {
       
  1786 #if defined QPROCESS_DEBUG
       
  1787     qDebug("QProcess::writeData(%p \"%s\", %lld) == 0 (write channel closing)",
       
  1788            data, qt_prettyDebug(data, len, 16).constData(), len);
       
  1789 #endif
       
  1790         return 0;
       
  1791     }
       
  1792 
       
  1793     if (len == 1) {
       
  1794         d->writeBuffer.putChar(*data);
       
  1795         if (d->stdinChannel.notifier)
       
  1796             d->stdinChannel.notifier->setEnabled(true);
       
  1797 #if defined QPROCESS_DEBUG
       
  1798     qDebug("QProcess::writeData(%p \"%s\", %lld) == 1 (written to buffer)",
       
  1799            data, qt_prettyDebug(data, len, 16).constData(), len);
       
  1800 #endif
       
  1801         return 1;
       
  1802     }
       
  1803 
       
  1804     char *dest = d->writeBuffer.reserve(len);
       
  1805     memcpy(dest, data, len);
       
  1806     if (d->stdinChannel.notifier)
       
  1807         d->stdinChannel.notifier->setEnabled(true);
       
  1808 #if defined QPROCESS_DEBUG
       
  1809     qDebug("QProcess::writeData(%p \"%s\", %lld) == %lld (written to buffer)",
       
  1810            data, qt_prettyDebug(data, len, 16).constData(), len, len);
       
  1811 #endif
       
  1812     return len;
       
  1813 }
       
  1814 
       
  1815 /*!
       
  1816     Regardless of the current read channel, this function returns all
       
  1817     data available from the standard output of the process as a
       
  1818     QByteArray.
       
  1819 
       
  1820     \sa readyReadStandardOutput(), readAllStandardError(), readChannel(), setReadChannel()
       
  1821 */
       
  1822 QByteArray QProcess::readAllStandardOutput()
       
  1823 {
       
  1824     ProcessChannel tmp = readChannel();
       
  1825     setReadChannel(StandardOutput);
       
  1826     QByteArray data = readAll();
       
  1827     setReadChannel(tmp);
       
  1828     return data;
       
  1829 }
       
  1830 
       
  1831 /*!
       
  1832     Regardless of the current read channel, this function returns all
       
  1833     data available from the standard error of the process as a
       
  1834     QByteArray.
       
  1835 
       
  1836     \sa readyReadStandardError(), readAllStandardOutput(), readChannel(), setReadChannel()
       
  1837 */
       
  1838 QByteArray QProcess::readAllStandardError()
       
  1839 {
       
  1840     ProcessChannel tmp = readChannel();
       
  1841     setReadChannel(StandardError);
       
  1842     QByteArray data = readAll();
       
  1843     setReadChannel(tmp);
       
  1844     return data;
       
  1845 }
       
  1846 
       
  1847 /*!
       
  1848     Starts the program \a program in a new process, if one is not already
       
  1849     running, passing the command line arguments in \a arguments. The OpenMode
       
  1850     is set to \a mode.
       
  1851 
       
  1852     The QProcess object will immediately enter the Starting state. If the
       
  1853     process starts successfully, QProcess will emit started(); otherwise,
       
  1854     error() will be emitted. If the QProcess object is already running a
       
  1855     process, a warning may be printed at the console, and the existing
       
  1856     process will continue running.
       
  1857 
       
  1858     \note Arguments that contain spaces are not passed to the
       
  1859     process as separate arguments.
       
  1860 
       
  1861     \note Processes are started asynchronously, which means the started()
       
  1862     and error() signals may be delayed. Call waitForStarted() to make
       
  1863     sure the process has started (or has failed to start) and those signals
       
  1864     have been emitted.
       
  1865 
       
  1866     \bold{Windows:} Arguments that contain spaces are wrapped in quotes.
       
  1867 
       
  1868     \sa pid(), started(), waitForStarted()
       
  1869 */
       
  1870 void QProcess::start(const QString &program, const QStringList &arguments, OpenMode mode)
       
  1871 {
       
  1872     Q_D(QProcess);
       
  1873     if (d->processState != NotRunning) {
       
  1874         qWarning("QProcess::start: Process is already running");
       
  1875         return;
       
  1876     }
       
  1877 
       
  1878 #if defined QPROCESS_DEBUG
       
  1879     qDebug() << "QProcess::start(" << program << ',' << arguments << ',' << mode << ')';
       
  1880 #endif
       
  1881 
       
  1882     d->outputReadBuffer.clear();
       
  1883     d->errorReadBuffer.clear();
       
  1884 
       
  1885     if (d->stdinChannel.type != QProcessPrivate::Channel::Normal)
       
  1886         mode &= ~WriteOnly;     // not open for writing
       
  1887     if (d->stdoutChannel.type != QProcessPrivate::Channel::Normal &&
       
  1888         (d->stderrChannel.type != QProcessPrivate::Channel::Normal ||
       
  1889          d->processChannelMode == MergedChannels))
       
  1890         mode &= ~ReadOnly;      // not open for reading
       
  1891     if (mode == 0)
       
  1892         mode = Unbuffered;
       
  1893     QIODevice::open(mode);
       
  1894 
       
  1895     d->stdinChannel.closed = false;
       
  1896     d->stdoutChannel.closed = false;
       
  1897     d->stderrChannel.closed = false;
       
  1898 
       
  1899     d->program = program;
       
  1900     d->arguments = arguments;
       
  1901 
       
  1902     d->exitCode = 0;
       
  1903     d->exitStatus = NormalExit;
       
  1904     d->processError = QProcess::UnknownError;
       
  1905     d->errorString.clear();
       
  1906     d->startProcess();
       
  1907 }
       
  1908 
       
  1909 
       
  1910 static QStringList parseCombinedArgString(const QString &program)
       
  1911 {
       
  1912     QStringList args;
       
  1913     QString tmp;
       
  1914     int quoteCount = 0;
       
  1915     bool inQuote = false;
       
  1916 
       
  1917     // handle quoting. tokens can be surrounded by double quotes
       
  1918     // "hello world". three consecutive double quotes represent
       
  1919     // the quote character itself.
       
  1920     for (int i = 0; i < program.size(); ++i) {
       
  1921         if (program.at(i) == QLatin1Char('"')) {
       
  1922             ++quoteCount;
       
  1923             if (quoteCount == 3) {
       
  1924                 // third consecutive quote
       
  1925                 quoteCount = 0;
       
  1926                 tmp += program.at(i);
       
  1927             }
       
  1928             continue;
       
  1929         }
       
  1930         if (quoteCount) {
       
  1931             if (quoteCount == 1)
       
  1932                 inQuote = !inQuote;
       
  1933             quoteCount = 0;
       
  1934         }
       
  1935         if (!inQuote && program.at(i).isSpace()) {
       
  1936             if (!tmp.isEmpty()) {
       
  1937                 args += tmp;
       
  1938                 tmp.clear();
       
  1939             }
       
  1940         } else {
       
  1941             tmp += program.at(i);
       
  1942         }
       
  1943     }
       
  1944     if (!tmp.isEmpty())
       
  1945         args += tmp;
       
  1946 
       
  1947     return args;
       
  1948 }
       
  1949 
       
  1950 /*!
       
  1951     \overload
       
  1952 
       
  1953     Starts the program \a program in a new process, if one is not already
       
  1954     running. \a program is a single string of text containing both the
       
  1955     program name and its arguments. The arguments are separated by one or
       
  1956     more spaces. For example:
       
  1957 
       
  1958     \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 5
       
  1959 
       
  1960     The \a program string can also contain quotes, to ensure that arguments
       
  1961     containing spaces are correctly supplied to the new process. For example:
       
  1962 
       
  1963     \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 6
       
  1964 
       
  1965     If the QProcess object is already running a process, a warning may be
       
  1966     printed at the console, and the existing process will continue running.
       
  1967 
       
  1968     Note that, on Windows, quotes need to be both escaped and quoted.
       
  1969     For example, the above code would be specified in the following
       
  1970     way to ensure that \c{"My Documents"} is used as the argument to
       
  1971     the \c dir executable:
       
  1972 
       
  1973     \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 7
       
  1974 
       
  1975     The OpenMode is set to \a mode.
       
  1976 */
       
  1977 void QProcess::start(const QString &program, OpenMode mode)
       
  1978 {
       
  1979     QStringList args = parseCombinedArgString(program);
       
  1980     if (args.isEmpty()) {
       
  1981         Q_D(QProcess);
       
  1982         d->processError = QProcess::FailedToStart;
       
  1983         setErrorString(tr("No program defined"));
       
  1984         emit error(d->processError);
       
  1985         return;
       
  1986     }
       
  1987 
       
  1988     QString prog = args.first();
       
  1989     args.removeFirst();
       
  1990 
       
  1991     start(prog, args, mode);
       
  1992 }
       
  1993 
       
  1994 /*!
       
  1995     Attempts to terminate the process.
       
  1996 
       
  1997     The process may not exit as a result of calling this function (it is given
       
  1998     the chance to prompt the user for any unsaved files, etc).
       
  1999 
       
  2000     On Windows, terminate() posts a WM_CLOSE message to all toplevel windows
       
  2001     of the process and then to the main thread of the process itself. On Unix
       
  2002     and Mac OS X the SIGTERM signal is sent.
       
  2003 
       
  2004     Console applications on Windows that do not run an event loop, or whose
       
  2005     event loop does not handle the WM_CLOSE message, can only be terminated by
       
  2006     calling kill().
       
  2007 
       
  2008     \note Terminating running processes from other processes will typically
       
  2009     cause a panic in Symbian due to platform security.
       
  2010 
       
  2011     \sa kill()
       
  2012 */
       
  2013 void QProcess::terminate()
       
  2014 {
       
  2015     Q_D(QProcess);
       
  2016     d->terminateProcess();
       
  2017 }
       
  2018 
       
  2019 /*!
       
  2020     Kills the current process, causing it to exit immediately.
       
  2021 
       
  2022     On Windows, kill() uses TerminateProcess, and on Unix and Mac OS X, the
       
  2023     SIGKILL signal is sent to the process.
       
  2024 
       
  2025     \sa terminate()
       
  2026 */
       
  2027 void QProcess::kill()
       
  2028 {
       
  2029     Q_D(QProcess);
       
  2030     d->killProcess();
       
  2031 }
       
  2032 
       
  2033 /*!
       
  2034     Returns the exit code of the last process that finished.
       
  2035 */
       
  2036 int QProcess::exitCode() const
       
  2037 {
       
  2038     Q_D(const QProcess);
       
  2039     return d->exitCode;
       
  2040 }
       
  2041 
       
  2042 /*!
       
  2043     \since 4.1
       
  2044 
       
  2045     Returns the exit status of the last process that finished.
       
  2046 
       
  2047     On Windows, if the process was terminated with TerminateProcess()
       
  2048     from another application this function will still return NormalExit
       
  2049     unless the exit code is less than 0.
       
  2050 */
       
  2051 QProcess::ExitStatus QProcess::exitStatus() const
       
  2052 {
       
  2053     Q_D(const QProcess);
       
  2054     return d->exitStatus;
       
  2055 }
       
  2056 
       
  2057 /*!
       
  2058     Starts the program \a program with the arguments \a arguments in a
       
  2059     new process, waits for it to finish, and then returns the exit
       
  2060     code of the process. Any data the new process writes to the
       
  2061     console is forwarded to the calling process.
       
  2062 
       
  2063     The environment and working directory are inherited by the calling
       
  2064     process.
       
  2065 
       
  2066     On Windows, arguments that contain spaces are wrapped in quotes.
       
  2067 */
       
  2068 int QProcess::execute(const QString &program, const QStringList &arguments)
       
  2069 {
       
  2070     QProcess process;
       
  2071     process.setReadChannelMode(ForwardedChannels);
       
  2072     process.start(program, arguments);
       
  2073     process.waitForFinished(-1);
       
  2074     return process.exitCode();
       
  2075 }
       
  2076 
       
  2077 /*!
       
  2078     \overload
       
  2079 
       
  2080     Starts the program \a program in a new process. \a program is a
       
  2081     single string of text containing both the program name and its
       
  2082     arguments. The arguments are separated by one or more spaces.
       
  2083 */
       
  2084 int QProcess::execute(const QString &program)
       
  2085 {
       
  2086     QProcess process;
       
  2087     process.setReadChannelMode(ForwardedChannels);
       
  2088     process.start(program);
       
  2089     process.waitForFinished(-1);
       
  2090     return process.exitCode();
       
  2091 }
       
  2092 
       
  2093 /*!
       
  2094     Starts the program \a program with the arguments \a arguments in a
       
  2095     new process, and detaches from it. Returns true on success;
       
  2096     otherwise returns false. If the calling process exits, the
       
  2097     detached process will continue to live.
       
  2098 
       
  2099     Note that arguments that contain spaces are not passed to the
       
  2100     process as separate arguments.
       
  2101 
       
  2102     \bold{Unix:} The started process will run in its own session and act
       
  2103     like a daemon.
       
  2104 
       
  2105     \bold{Windows:} Arguments that contain spaces are wrapped in quotes.
       
  2106     The started process will run as a regular standalone process.
       
  2107 
       
  2108     The process will be started in the directory \a workingDirectory.
       
  2109 
       
  2110     If the function is successful then *\a pid is set to the process
       
  2111     identifier of the started process.
       
  2112 */
       
  2113 bool QProcess::startDetached(const QString &program,
       
  2114 			     const QStringList &arguments,
       
  2115 			     const QString &workingDirectory,
       
  2116                              qint64 *pid)
       
  2117 {
       
  2118     return QProcessPrivate::startDetached(program,
       
  2119 					  arguments,
       
  2120 					  workingDirectory,
       
  2121 					  pid);
       
  2122 }
       
  2123 
       
  2124 /*!
       
  2125     Starts the program \a program with the given \a arguments in a
       
  2126     new process, and detaches from it. Returns true on success;
       
  2127     otherwise returns false. If the calling process exits, the
       
  2128     detached process will continue to live.
       
  2129 
       
  2130     \note Arguments that contain spaces are not passed to the
       
  2131     process as separate arguments.
       
  2132 
       
  2133     \bold{Unix:} The started process will run in its own session and act
       
  2134     like a daemon.
       
  2135 
       
  2136     \bold{Windows:} Arguments that contain spaces are wrapped in quotes.
       
  2137     The started process will run as a regular standalone process.
       
  2138 */
       
  2139 bool QProcess::startDetached(const QString &program,
       
  2140 			     const QStringList &arguments)
       
  2141 {
       
  2142     return QProcessPrivate::startDetached(program, arguments);
       
  2143 }
       
  2144 
       
  2145 /*!
       
  2146     \overload
       
  2147 
       
  2148     Starts the program \a program in a new process. \a program is a
       
  2149     single string of text containing both the program name and its
       
  2150     arguments. The arguments are separated by one or more spaces.
       
  2151 
       
  2152     The \a program string can also contain quotes, to ensure that arguments
       
  2153     containing spaces are correctly supplied to the new process.
       
  2154 */
       
  2155 bool QProcess::startDetached(const QString &program)
       
  2156 {
       
  2157     QStringList args = parseCombinedArgString(program);
       
  2158     if (args.isEmpty())
       
  2159         return false;
       
  2160 
       
  2161     QString prog = args.first();
       
  2162     args.removeFirst();
       
  2163 
       
  2164     return QProcessPrivate::startDetached(prog, args);
       
  2165 }
       
  2166 
       
  2167 QT_BEGIN_INCLUDE_NAMESPACE
       
  2168 #ifdef Q_OS_MAC
       
  2169 # include <crt_externs.h>
       
  2170 # define environ (*_NSGetEnviron())
       
  2171 #elif defined(Q_OS_WINCE) || defined(Q_OS_SYMBIAN)
       
  2172   static char *qt_empty_environ[] = { 0 };
       
  2173 #define environ qt_empty_environ
       
  2174 #elif !defined(Q_OS_WIN)
       
  2175   extern char **environ;
       
  2176 #endif
       
  2177 QT_END_INCLUDE_NAMESPACE
       
  2178 
       
  2179 /*!
       
  2180     \since 4.1
       
  2181 
       
  2182     Returns the environment of the calling process as a list of
       
  2183     key=value pairs. Example:
       
  2184 
       
  2185     \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 8
       
  2186 
       
  2187     This function does not cache the system environment. Therefore, it's
       
  2188     possible to obtain an updated version of the environment if low-level C
       
  2189     library functions like \tt setenv ot \tt putenv have been called.
       
  2190 
       
  2191     However, note that repeated calls to this function will recreate the
       
  2192     list of environment variables, which is a non-trivial operation.
       
  2193 
       
  2194     \note For new code, it is recommended to use QProcessEvironment::systemEnvironment()
       
  2195 
       
  2196     \sa QProcessEnvironment::systemEnvironment(), environment(), setEnvironment()
       
  2197 */
       
  2198 QStringList QProcess::systemEnvironment()
       
  2199 {
       
  2200     QStringList tmp;
       
  2201     char *entry = 0;
       
  2202     int count = 0;
       
  2203     while ((entry = environ[count++]))
       
  2204         tmp << QString::fromLocal8Bit(entry);
       
  2205     return tmp;
       
  2206 }
       
  2207 
       
  2208 /*!
       
  2209     \since 4.6
       
  2210 
       
  2211     \brief The systemEnvironment function returns the environment of
       
  2212     the calling process.
       
  2213 
       
  2214     It is returned as a QProcessEnvironment. This function does not
       
  2215     cache the system environment. Therefore, it's possible to obtain
       
  2216     an updated version of the environment if low-level C library
       
  2217     functions like \tt setenv ot \tt putenv have been called.
       
  2218 
       
  2219     However, note that repeated calls to this function will recreate the
       
  2220     QProcessEnvironment object, which is a non-trivial operation.
       
  2221 
       
  2222     \sa QProcess::systemEnvironment()
       
  2223 */
       
  2224 QProcessEnvironment QProcessEnvironment::systemEnvironment()
       
  2225 {
       
  2226     QProcessEnvironment env;
       
  2227     const char *entry;
       
  2228     for (int count = 0; (entry = environ[count]); ++count) {
       
  2229         const char *equal = strchr(entry, '=');
       
  2230         if (!equal)
       
  2231             continue;
       
  2232 
       
  2233         QByteArray name(entry, equal - entry);
       
  2234         QByteArray value(equal + 1);
       
  2235         env.insert(QString::fromLocal8Bit(name), QString::fromLocal8Bit(value));
       
  2236     }
       
  2237     return env;
       
  2238 }
       
  2239 
       
  2240 /*!
       
  2241     \typedef Q_PID
       
  2242     \relates QProcess
       
  2243 
       
  2244     Typedef for the identifiers used to represent processes on the underlying
       
  2245     platform. On Unix and Symbian, this corresponds to \l qint64; on Windows, it
       
  2246     corresponds to \c{_PROCESS_INFORMATION*}.
       
  2247 
       
  2248     \sa QProcess::pid()
       
  2249 */
       
  2250 
       
  2251 QT_END_NAMESPACE
       
  2252 
       
  2253 #include "moc_qprocess.cpp"
       
  2254 
       
  2255 #endif // QT_NO_PROCESS
       
  2256