1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtCore module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 //#define QPROCESS_DEBUG
44 #if defined QPROCESS_DEBUG
48 #if !defined(Q_OS_WINCE)
54 Returns a human readable representation of the first \a len
55 characters in \a data.
57 static QByteArray qt_prettyDebug(const char *data, int len, int maxSize)
59 if (!data) return "(null)";
61 for (int i = 0; i < len && i < maxSize; ++i) {
66 case '\n': out += "\\n"; break;
67 case '\r': out += "\\r"; break;
68 case '\t': out += "\\t"; break;
71 qsnprintf(buf, sizeof(buf), "\\%3o", c);
73 out += QByteArray(buf);
88 #include "qprocess_p.h"
90 #include <qbytearray.h>
91 #include <qelapsedtimer.h>
92 #include <qcoreapplication.h>
93 #include <qsocketnotifier.h>
97 #include <qwineventnotifier.h>
104 #ifndef QT_NO_PROCESS
109 \class QProcessEnvironment
111 \brief The QProcessEnvironment class holds the environment variables that
112 can be passed to a program.
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.
126 The environment of the calling process can be obtained using
127 QProcessEnvironment::systemEnvironment().
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).
136 On Windows, the variable names are case-insensitive. Therefore,
137 QProcessEnvironment will always uppercase the names and do case-insensitive
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.
144 \sa QProcess, QProcess::systemEnvironment(), QProcess::setProcessEnvironment()
147 QStringList QProcessEnvironmentPrivate::toList() const
150 result.reserve(hash.size());
151 Hash::ConstIterator it = hash.constBegin(),
152 end = hash.constEnd();
153 for ( ; it != end; ++it) {
154 QString data = nameToString(it.key());
155 QString value = valueToString(it.value());
156 data.reserve(data.length() + value.length() + 1);
157 data.append(QLatin1Char('='));
164 QProcessEnvironment QProcessEnvironmentPrivate::fromList(const QStringList &list)
166 QProcessEnvironment env;
167 QStringList::ConstIterator it = list.constBegin(),
168 end = list.constEnd();
169 for ( ; it != end; ++it) {
170 int pos = it->indexOf(QLatin1Char('='));
174 QString value = it->mid(pos + 1);
177 env.insert(name, value);
182 QStringList QProcessEnvironmentPrivate::keys() const
185 result.reserve(hash.size());
186 Hash::ConstIterator it = hash.constBegin(),
187 end = hash.constEnd();
188 for ( ; it != end; ++it)
189 result << nameToString(it.key());
193 void QProcessEnvironmentPrivate::insert(const QProcessEnvironmentPrivate &other)
195 Hash::ConstIterator it = other.hash.constBegin(),
196 end = other.hash.constEnd();
197 for ( ; it != end; ++it)
198 hash.insert(it.key(), it.value());
201 QHash<QString, Key>::ConstIterator nit = other.nameMap.constBegin(),
202 nend = other.nameMap.constEnd();
203 for ( ; nit != nend; ++nit)
204 nameMap.insert(nit.key(), nit.value());
209 Creates a new QProcessEnvironment object. This constructor creates an
210 empty environment. If set on a QProcess, this will cause the current
211 environment variables to be removed.
213 QProcessEnvironment::QProcessEnvironment()
219 Frees the resources associated with this QProcessEnvironment object.
221 QProcessEnvironment::~QProcessEnvironment()
226 Creates a QProcessEnvironment object that is a copy of \a other.
228 QProcessEnvironment::QProcessEnvironment(const QProcessEnvironment &other)
234 Copies the contents of the \a other QProcessEnvironment object into this
237 QProcessEnvironment &QProcessEnvironment::operator=(const QProcessEnvironment &other)
244 \fn bool QProcessEnvironment::operator !=(const QProcessEnvironment &other) const
246 Returns true if this and the \a other QProcessEnvironment objects are different.
252 Returns true if this and the \a other QProcessEnvironment objects are equal.
254 Two QProcessEnvironment objects are considered equal if they have the same
255 set of key=value pairs. The comparison of keys is done case-sensitive on
256 platforms where the environment is case-sensitive.
258 \sa operator!=(), contains()
260 bool QProcessEnvironment::operator==(const QProcessEnvironment &other) const
262 return d == other.d || (d && other.d && d->hash == other.d->hash);
266 Returns true if this QProcessEnvironment object is empty: that is
267 there are no key=value pairs set.
269 \sa clear(), systemEnvironment(), insert()
271 bool QProcessEnvironment::isEmpty() const
273 return d ? d->hash.isEmpty() : true;
277 Removes all key=value pairs from this QProcessEnvironment object, making
280 \sa isEmpty(), systemEnvironment()
282 void QProcessEnvironment::clear()
286 // Unix: Don't clear d->nameMap, as the environment is likely to be
287 // re-populated with the same keys again.
291 Returns true if the environment variable of name \a name is found in
292 this QProcessEnvironment object.
294 On Windows, variable names are case-insensitive, so the key is converted
295 to uppercase before searching. On other systems, names are case-sensitive
296 so no trasformation is applied.
298 \sa insert(), value()
300 bool QProcessEnvironment::contains(const QString &name) const
302 return d ? d->hash.contains(d->prepareName(name)) : false;
306 Inserts the environment variable of name \a name and contents \a value
307 into this QProcessEnvironment object. If that variable already existed,
308 it is replaced by the new value.
310 On Windows, variable names are case-insensitive, so this function always
311 uppercases the variable name before inserting. On other systems, names
312 are case-sensitive, so no transformation is applied.
314 On most systems, inserting a variable with no contents will have the
315 same effect for applications as if the variable had not been set at all.
316 However, to guarantee that there are no incompatibilities, to remove a
317 variable, please use the remove() function.
319 \sa contains(), remove(), value()
321 void QProcessEnvironment::insert(const QString &name, const QString &value)
323 // d detaches from null
324 d->hash.insert(d->prepareName(name), d->prepareValue(value));
328 Removes the environment variable identified by \a name from this
329 QProcessEnvironment object. If that variable did not exist before,
332 On Windows, variable names are case-insensitive, so the key is converted
333 to uppercase before searching. On other systems, names are case-sensitive
334 so no trasformation is applied.
336 \sa contains(), insert(), value()
338 void QProcessEnvironment::remove(const QString &name)
341 d->hash.remove(d->prepareName(name));
345 Searches this QProcessEnvironment object for a variable identified by
346 \a name and returns its value. If the variable is not found in this object,
347 then \a defaultValue is returned instead.
349 On Windows, variable names are case-insensitive, so the key is converted
350 to uppercase before searching. On other systems, names are case-sensitive
351 so no trasformation is applied.
353 \sa contains(), insert(), remove()
355 QString QProcessEnvironment::value(const QString &name, const QString &defaultValue) const
360 QProcessEnvironmentPrivate::Hash::ConstIterator it = d->hash.constFind(d->prepareName(name));
361 if (it == d->hash.constEnd())
364 return d->valueToString(it.value());
368 Converts this QProcessEnvironment object into a list of strings, one for
369 each environment variable that is set. The environment variable's name
370 and its value are separated by an equal character ('=').
372 The QStringList contents returned by this function are suitable for use
373 with the QProcess::setEnvironment function. However, it is recommended
374 to use QProcess::setProcessEnvironment instead since that will avoid
375 unnecessary copying of the data.
377 \sa systemEnvironment(), QProcess::systemEnvironment(), QProcess::environment(),
378 QProcess::setEnvironment()
380 QStringList QProcessEnvironment::toStringList() const
382 return d ? d->toList() : QStringList();
388 Returns a list containing all the variable names in this QProcessEnvironment
391 QStringList QProcessEnvironment::keys() const
393 return d ? d->keys() : QStringList();
400 Inserts the contents of \a e in this QProcessEnvironment object. Variables in
401 this object that also exist in \a e will be overwritten.
403 void QProcessEnvironment::insert(const QProcessEnvironment &e)
408 // d detaches from null
412 void QProcessPrivate::Channel::clear()
417 process->stdinChannel.type = Normal;
418 process->stdinChannel.process = 0;
422 process->stdoutChannel.type = Normal;
423 process->stdoutChannel.process = 0;
432 /*! \fn bool QProcessPrivate::startDetached(const QString &program, const QStringList &arguments, const QString &workingDirectory, qint64 *pid)
440 \brief The QProcess class is used to start external programs and
441 to communicate with them.
447 \section1 Running a Process
449 To start a process, pass the name and command line arguments of
450 the program you want to run as arguments to start(). Arguments
451 are supplied as individual strings in a QStringList.
453 For example, the following code snippet runs the analog clock
454 example in the Motif style on X11 platforms by passing strings
455 containing "-style" and "motif" as two items in the list of
458 \snippet doc/src/snippets/qprocess/qprocess-simpleexecution.cpp 0
460 \snippet doc/src/snippets/qprocess/qprocess-simpleexecution.cpp 1
461 \snippet doc/src/snippets/qprocess/qprocess-simpleexecution.cpp 2
463 QProcess then enters the \l Starting state, and when the program
464 has started, QProcess enters the \l Running state and emits
467 QProcess allows you to treat a process as a sequential I/O
468 device. You can write to and read from the process just as you
469 would access a network connection using QTcpSocket. You can then
470 write to the process's standard input by calling write(), and
471 read the standard output by calling read(), readLine(), and
472 getChar(). Because it inherits QIODevice, QProcess can also be
473 used as an input source for QXmlReader, or for generating data to
474 be uploaded using QNetworkAccessManager.
476 \note On Windows CE and Symbian, reading and writing to a process
479 When the process exits, QProcess reenters the \l NotRunning state
480 (the initial state), and emits finished().
482 The finished() signal provides the exit code and exit status of
483 the process as arguments, and you can also call exitCode() to
484 obtain the exit code of the last process that finished, and
485 exitStatus() to obtain its exit status. If an error occurs at
486 any point in time, QProcess will emit the error() signal. You
487 can also call error() to find the type of error that occurred
488 last, and state() to find the current process state.
490 \section1 Communicating via Channels
492 Processes have two predefined output channels: The standard
493 output channel (\c stdout) supplies regular console output, and
494 the standard error channel (\c stderr) usually supplies the
495 errors that are printed by the process. These channels represent
496 two separate streams of data. You can toggle between them by
497 calling setReadChannel(). QProcess emits readyRead() when data is
498 available on the current read channel. It also emits
499 readyReadStandardOutput() when new standard output data is
500 available, and when new standard error data is available,
501 readyReadStandardError() is emitted. Instead of calling read(),
502 readLine(), or getChar(), you can explicitly read all data from
503 either of the two channels by calling readAllStandardOutput() or
504 readAllStandardError().
506 The terminology for the channels can be misleading. Be aware that
507 the process's output channels correspond to QProcess's
508 \e read channels, whereas the process's input channels correspond
509 to QProcess's \e write channels. This is because what we read
510 using QProcess is the process's output, and what we write becomes
513 QProcess can merge the two output channels, so that standard
514 output and standard error data from the running process both use
515 the standard output channel. Call setProcessChannelMode() with
516 MergedChannels before starting the process to activative
517 this feature. You also have the option of forwarding the output of
518 the running process to the calling, main process, by passing
519 ForwardedChannels as the argument.
521 Certain processes need special environment settings in order to
522 operate. You can set environment variables for your process by
523 calling setEnvironment(). To set a working directory, call
524 setWorkingDirectory(). By default, processes are run in the
525 current working directory of the calling process.
527 \note On Symbian, setting environment or working directory
528 is not supported. The working directory will always be the private
529 directory of the running process.
531 \section1 Synchronous Process API
533 QProcess provides a set of functions which allow it to be used
534 without an event loop, by suspending the calling thread until
535 certain signals are emitted:
538 \o waitForStarted() blocks until the process has started.
540 \o waitForReadyRead() blocks until new data is
541 available for reading on the current read channel.
543 \o waitForBytesWritten() blocks until one payload of
544 data has been written to the process.
546 \o waitForFinished() blocks until the process has finished.
549 Calling these functions from the main thread (the thread that
550 calls QApplication::exec()) may cause your user interface to
553 The following example runs \c gzip to compress the string "Qt
554 rocks!", without an event loop:
556 \snippet doc/src/snippets/process/process.cpp 0
558 \section1 Notes for Windows Users
560 Some Windows commands (for example, \c dir) are not provided by
561 separate applications, but by the command interpreter itself.
562 If you attempt to use QProcess to execute these commands directly,
563 it won't work. One possible solution is to execute the command
564 interpreter itself (\c{cmd.exe} on some Windows systems), and ask
565 the interpreter to execute the desired command.
567 \section1 Symbian Platform Security Requirements
569 On Symbian, processes which use the functions kill() or terminate()
570 must have the \c PowerMgmt platform security capability. If the client
571 process lacks this capability, these functions will fail.
573 Platform security capabilities are added via the
574 \l{qmake-variable-reference.html#target-capability}{TARGET.CAPABILITY}
577 \sa QBuffer, QFile, QTcpSocket
581 \enum QProcess::ProcessChannel
583 This enum describes the process channels used by the running process.
584 Pass one of these values to setReadChannel() to set the
585 current read channel of QProcess.
587 \value StandardOutput The standard output (stdout) of the running
590 \value StandardError The standard error (stderr) of the running
597 \enum QProcess::ProcessChannelMode
599 This enum describes the process channel modes of QProcess. Pass
600 one of these values to setProcessChannelMode() to set the
601 current read channel mode.
603 \value SeparateChannels QProcess manages the output of the
604 running process, keeping standard output and standard error data
605 in separate internal buffers. You can select the QProcess's
606 current read channel by calling setReadChannel(). This is the
607 default channel mode of QProcess.
609 \value MergedChannels QProcess merges the output of the running
610 process into the standard output channel (\c stdout). The
611 standard error channel (\c stderr) will not receive any data. The
612 standard output and standard error data of the running process
615 \value ForwardedChannels QProcess forwards the output of the
616 running process onto the main process. Anything the child process
617 writes to its standard output and standard error will be written
618 to the standard output and standard error of the main process.
620 \note Windows intentionally suppresses output from GUI-only
621 applications to inherited consoles.
622 This does \e not apply to output redirected to files or pipes.
623 To forward the output of GUI-only applications on the console
624 nonetheless, you must use SeparateChannels and do the forwarding
625 yourself by reading the output and writing it to the appropriate
628 \sa setProcessChannelMode()
632 \enum QProcess::ProcessError
634 This enum describes the different types of errors that are
635 reported by QProcess.
637 \value FailedToStart The process failed to start. Either the
638 invoked program is missing, or you may have insufficient
639 permissions to invoke the program.
641 \value Crashed The process crashed some time after starting
644 \value Timedout The last waitFor...() function timed out. The
645 state of QProcess is unchanged, and you can try calling
648 \value WriteError An error occurred when attempting to write to the
649 process. For example, the process may not be running, or it may
650 have closed its input channel.
652 \value ReadError An error occurred when attempting to read from
653 the process. For example, the process may not be running.
655 \value UnknownError An unknown error occurred. This is the default
656 return value of error().
662 \enum QProcess::ProcessState
664 This enum describes the different states of QProcess.
666 \value NotRunning The process is not running.
668 \value Starting The process is starting, but the program has not
671 \value Running The process is running and is ready for reading and
678 \enum QProcess::ExitStatus
680 This enum describes the different exit statuses of QProcess.
682 \value NormalExit The process exited normally.
684 \value CrashExit The process crashed.
690 \fn void QProcess::error(QProcess::ProcessError error)
692 This signal is emitted when an error occurs with the process. The
693 specified \a error describes the type of error that occurred.
697 \fn void QProcess::started()
699 This signal is emitted by QProcess when the process has started,
700 and state() returns \l Running.
704 \fn void QProcess::stateChanged(QProcess::ProcessState newState)
706 This signal is emitted whenever the state of QProcess changes. The
707 \a newState argument is the state QProcess changed to.
711 \fn void QProcess::finished(int exitCode)
715 Use finished(int exitCode, QProcess::ExitStatus status) instead.
719 \fn void QProcess::finished(int exitCode, QProcess::ExitStatus exitStatus)
721 This signal is emitted when the process finishes. \a exitCode is the exit
722 code of the process, and \a exitStatus is the exit status. After the
723 process has finished, the buffers in QProcess are still intact. You can
724 still read any data that the process may have written before it finished.
730 \fn void QProcess::readyReadStandardOutput()
732 This signal is emitted when the process has made new data
733 available through its standard output channel (\c stdout). It is
734 emitted regardless of the current \l{readChannel()}{read channel}.
736 \sa readAllStandardOutput(), readChannel()
740 \fn void QProcess::readyReadStandardError()
742 This signal is emitted when the process has made new data
743 available through its standard error channel (\c stderr). It is
744 emitted regardless of the current \l{readChannel()}{read
747 \sa readAllStandardError(), readChannel()
752 QProcessPrivate::QProcessPrivate()
754 processChannel = QProcess::StandardOutput;
755 processChannelMode = QProcess::SeparateChannels;
756 processError = QProcess::UnknownError;
757 processState = QProcess::NotRunning;
761 exitStatus = QProcess::NormalExit;
762 startupSocketNotifier = 0;
766 childStartedPipe[0] = INVALID_Q_PIPE;
767 childStartedPipe[1] = INVALID_Q_PIPE;
768 deathPipe[0] = INVALID_Q_PIPE;
769 deathPipe[1] = INVALID_Q_PIPE;
773 emittedReadyRead = false;
774 emittedBytesWritten = false;
777 processFinishedNotifier = 0;
783 symbianProcess = NULL;
784 processLaunched = false;
790 QProcessPrivate::~QProcessPrivate()
792 if (stdinChannel.process)
793 stdinChannel.process->stdoutChannel.clear();
794 if (stdoutChannel.process)
795 stdoutChannel.process->stdinChannel.clear();
800 void QProcessPrivate::cleanup()
802 q_func()->setProcessState(QProcess::NotRunning);
805 CloseHandle(pid->hThread);
806 CloseHandle(pid->hProcess);
810 if (processFinishedNotifier) {
811 processFinishedNotifier->setEnabled(false);
812 qDeleteInEventHandler(processFinishedNotifier);
813 processFinishedNotifier = 0;
821 if (stdoutChannel.notifier) {
822 stdoutChannel.notifier->setEnabled(false);
823 qDeleteInEventHandler(stdoutChannel.notifier);
824 stdoutChannel.notifier = 0;
826 if (stderrChannel.notifier) {
827 stderrChannel.notifier->setEnabled(false);
828 qDeleteInEventHandler(stderrChannel.notifier);
829 stderrChannel.notifier = 0;
831 if (stdinChannel.notifier) {
832 stdinChannel.notifier->setEnabled(false);
833 qDeleteInEventHandler(stdinChannel.notifier);
834 stdinChannel.notifier = 0;
836 if (startupSocketNotifier) {
837 startupSocketNotifier->setEnabled(false);
838 qDeleteInEventHandler(startupSocketNotifier);
839 startupSocketNotifier = 0;
842 deathNotifier->setEnabled(false);
843 qDeleteInEventHandler(deathNotifier);
847 qDeleteInEventHandler(notifier);
850 destroyPipe(stdoutChannel.pipe);
851 destroyPipe(stderrChannel.pipe);
852 destroyPipe(stdinChannel.pipe);
853 destroyPipe(childStartedPipe);
854 destroyPipe(deathPipe);
859 if (symbianProcess) {
860 symbianProcess->Close();
861 delete symbianProcess;
862 symbianProcess = NULL;
869 bool QProcessPrivate::_q_canReadStandardOutput()
872 qint64 available = bytesAvailableFromStdout();
873 if (available == 0) {
874 if (stdoutChannel.notifier)
875 stdoutChannel.notifier->setEnabled(false);
876 destroyPipe(stdoutChannel.pipe);
877 #if defined QPROCESS_DEBUG
878 qDebug("QProcessPrivate::canReadStandardOutput(), 0 bytes available");
883 char *ptr = outputReadBuffer.reserve(available);
884 qint64 readBytes = readFromStdout(ptr, available);
885 if (readBytes == -1) {
886 processError = QProcess::ReadError;
887 q->setErrorString(QProcess::tr("Error reading from process"));
888 emit q->error(processError);
889 #if defined QPROCESS_DEBUG
890 qDebug("QProcessPrivate::canReadStandardOutput(), failed to read from the process");
894 #if defined QPROCESS_DEBUG
895 qDebug("QProcessPrivate::canReadStandardOutput(), read %d bytes from the process' output",
899 if (stdoutChannel.closed) {
900 outputReadBuffer.chop(readBytes);
904 outputReadBuffer.chop(available - readBytes);
906 bool didRead = false;
907 if (readBytes == 0) {
908 if (stdoutChannel.notifier)
909 stdoutChannel.notifier->setEnabled(false);
910 } else if (processChannel == QProcess::StandardOutput) {
912 if (!emittedReadyRead) {
913 emittedReadyRead = true;
915 emittedReadyRead = false;
918 emit q->readyReadStandardOutput();
924 bool QProcessPrivate::_q_canReadStandardError()
927 qint64 available = bytesAvailableFromStderr();
928 if (available == 0) {
929 if (stderrChannel.notifier)
930 stderrChannel.notifier->setEnabled(false);
931 destroyPipe(stderrChannel.pipe);
935 char *ptr = errorReadBuffer.reserve(available);
936 qint64 readBytes = readFromStderr(ptr, available);
937 if (readBytes == -1) {
938 processError = QProcess::ReadError;
939 q->setErrorString(QProcess::tr("Error reading from process"));
940 emit q->error(processError);
943 if (stderrChannel.closed) {
944 errorReadBuffer.chop(readBytes);
948 errorReadBuffer.chop(available - readBytes);
950 bool didRead = false;
951 if (readBytes == 0) {
952 if (stderrChannel.notifier)
953 stderrChannel.notifier->setEnabled(false);
954 } else if (processChannel == QProcess::StandardError) {
956 if (!emittedReadyRead) {
957 emittedReadyRead = true;
959 emittedReadyRead = false;
962 emit q->readyReadStandardError();
968 bool QProcessPrivate::_q_canWrite()
971 if (stdinChannel.notifier)
972 stdinChannel.notifier->setEnabled(false);
974 if (writeBuffer.isEmpty()) {
975 #if defined QPROCESS_DEBUG
976 qDebug("QProcessPrivate::canWrite(), not writing anything (empty write buffer).");
981 qint64 written = writeToStdin(writeBuffer.readPointer(),
982 writeBuffer.nextDataBlockSize());
984 destroyPipe(stdinChannel.pipe);
985 processError = QProcess::WriteError;
986 q->setErrorString(QProcess::tr("Error writing to process"));
987 emit q->error(processError);
991 #if defined QPROCESS_DEBUG
992 qDebug("QProcessPrivate::canWrite(), wrote %d bytes to the process input", int(written));
996 writeBuffer.free(written);
997 if (!emittedBytesWritten) {
998 emittedBytesWritten = true;
999 emit q->bytesWritten(written);
1000 emittedBytesWritten = false;
1003 if (stdinChannel.notifier && !writeBuffer.isEmpty())
1004 stdinChannel.notifier->setEnabled(true);
1005 if (writeBuffer.isEmpty() && stdinChannel.closed)
1006 closeWriteChannel();
1012 bool QProcessPrivate::_q_processDied()
1015 #if defined QPROCESS_DEBUG
1016 qDebug("QProcessPrivate::_q_processDied()");
1019 if (!waitForDeadChild())
1023 if (processFinishedNotifier)
1024 processFinishedNotifier->setEnabled(false);
1027 // the process may have died before it got a chance to report that it was
1028 // either running or stopped, so we will call _q_startupNotification() and
1029 // give it a chance to emit started() or error(FailedToStart).
1030 if (processState == QProcess::Starting) {
1031 if (!_q_startupNotification())
1036 // at this point we know the process is dead. prevent
1037 // reentering this slot recursively by calling waitForFinished()
1038 // or opening a dialog inside slots connected to the readyRead
1039 // signals emitted below.
1044 // in case there is data in the pipe line and this slot by chance
1045 // got called before the read notifications, call these two slots
1046 // so the data is made available before the process dies.
1047 _q_canReadStandardOutput();
1048 _q_canReadStandardError();
1053 exitStatus = QProcess::CrashExit;
1054 processError = QProcess::Crashed;
1055 q->setErrorString(QProcess::tr("Process crashed"));
1056 emit q->error(processError);
1059 bool wasRunning = (processState == QProcess::Running);
1064 // we received EOF now:
1065 emit q->readChannelFinished();
1067 //emit q->standardOutputClosed();
1068 //emit q->standardErrorClosed();
1070 emit q->finished(exitCode);
1071 emit q->finished(exitCode, exitStatus);
1073 #if defined QPROCESS_DEBUG
1074 qDebug("QProcessPrivate::_q_processDied() process is dead");
1081 bool QProcessPrivate::_q_startupNotification()
1084 #if defined QPROCESS_DEBUG
1085 qDebug("QProcessPrivate::startupNotification()");
1088 if (startupSocketNotifier)
1089 startupSocketNotifier->setEnabled(false);
1090 if (processStarted()) {
1091 q->setProcessState(QProcess::Running);
1096 q->setProcessState(QProcess::NotRunning);
1097 processError = QProcess::FailedToStart;
1098 emit q->error(processError);
1100 // make sure the process manager removes this entry
1110 void QProcessPrivate::closeWriteChannel()
1112 #if defined QPROCESS_DEBUG
1113 qDebug("QProcessPrivate::closeWriteChannel()");
1115 if (stdinChannel.notifier) {
1116 extern void qDeleteInEventHandler(QObject *o);
1117 stdinChannel.notifier->setEnabled(false);
1118 if (stdinChannel.notifier) {
1119 qDeleteInEventHandler(stdinChannel.notifier);
1120 stdinChannel.notifier = 0;
1124 // ### Find a better fix, feeding the process little by little
1128 destroyPipe(stdinChannel.pipe);
1132 Constructs a QProcess object with the given \a parent.
1134 QProcess::QProcess(QObject *parent)
1135 : QIODevice(*new QProcessPrivate, parent)
1137 #if defined QPROCESS_DEBUG
1138 qDebug("QProcess::QProcess(%p)", parent);
1143 Destructs the QProcess object, i.e., killing the process.
1145 Note that this function will not return until the process is
1148 QProcess::~QProcess()
1151 if (d->processState != NotRunning) {
1152 qWarning("QProcess: Destroyed while process is still running.");
1157 // make sure the process manager removes this entry
1165 Returns the read channel mode of the QProcess. This function is
1166 equivalent to processChannelMode()
1168 \sa processChannelMode()
1170 QProcess::ProcessChannelMode QProcess::readChannelMode() const
1172 return processChannelMode();
1178 Use setProcessChannelMode(\a mode) instead.
1180 \sa setProcessChannelMode()
1182 void QProcess::setReadChannelMode(ProcessChannelMode mode)
1184 setProcessChannelMode(mode);
1190 Returns the channel mode of the QProcess standard output and
1191 standard error channels.
1193 \sa setProcessChannelMode(), ProcessChannelMode, setReadChannel()
1195 QProcess::ProcessChannelMode QProcess::processChannelMode() const
1197 Q_D(const QProcess);
1198 return d->processChannelMode;
1204 Sets the channel mode of the QProcess standard output and standard
1205 error channels to the \a mode specified.
1206 This mode will be used the next time start() is called. For example:
1208 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 0
1210 \sa processChannelMode(), ProcessChannelMode, setReadChannel()
1212 void QProcess::setProcessChannelMode(ProcessChannelMode mode)
1215 d->processChannelMode = mode;
1219 Returns the current read channel of the QProcess.
1221 \sa setReadChannel()
1223 QProcess::ProcessChannel QProcess::readChannel() const
1225 Q_D(const QProcess);
1226 return d->processChannel;
1230 Sets the current read channel of the QProcess to the given \a
1231 channel. The current input channel is used by the functions
1232 read(), readAll(), readLine(), and getChar(). It also determines
1233 which channel triggers QProcess to emit readyRead().
1237 void QProcess::setReadChannel(ProcessChannel channel)
1240 if (d->processChannel != channel) {
1241 QByteArray buf = d->buffer.readAll();
1242 if (d->processChannel == QProcess::StandardOutput) {
1243 for (int i = buf.size() - 1; i >= 0; --i)
1244 d->outputReadBuffer.ungetChar(buf.at(i));
1246 for (int i = buf.size() - 1; i >= 0; --i)
1247 d->errorReadBuffer.ungetChar(buf.at(i));
1250 d->processChannel = channel;
1254 Closes the read channel \a channel. After calling this function,
1255 QProcess will no longer receive data on the channel. Any data that
1256 has already been received is still available for reading.
1258 Call this function to save memory, if you are not interested in
1259 the output of the process.
1261 \sa closeWriteChannel(), setReadChannel()
1263 void QProcess::closeReadChannel(ProcessChannel channel)
1267 if (channel == StandardOutput)
1268 d->stdoutChannel.closed = true;
1270 d->stderrChannel.closed = true;
1274 Schedules the write channel of QProcess to be closed. The channel
1275 will close once all data has been written to the process. After
1276 calling this function, any attempts to write to the process will
1279 Closing the write channel is necessary for programs that read
1280 input data until the channel has been closed. For example, the
1281 program "more" is used to display text data in a console on both
1282 Unix and Windows. But it will not display the text data until
1283 QProcess's write channel has been closed. Example:
1285 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 1
1287 The write channel is implicitly opened when start() is called.
1289 \sa closeReadChannel()
1291 void QProcess::closeWriteChannel()
1294 d->stdinChannel.closed = true; // closing
1295 if (d->writeBuffer.isEmpty())
1296 d->closeWriteChannel();
1302 Redirects the process' standard input to the file indicated by \a
1303 fileName. When an input redirection is in place, the QProcess
1304 object will be in read-only mode (calling write() will result in
1307 If the file \a fileName does not exist at the moment start() is
1308 called or is not readable, starting the process will fail.
1310 Calling setStandardInputFile() after the process has started has no
1313 \sa setStandardOutputFile(), setStandardErrorFile(),
1314 setStandardOutputProcess()
1316 void QProcess::setStandardInputFile(const QString &fileName)
1319 d->stdinChannel = fileName;
1325 Redirects the process' standard output to the file \a
1326 fileName. When the redirection is in place, the standard output
1327 read channel is closed: reading from it using read() will always
1328 fail, as will readAllStandardOutput().
1330 If the file \a fileName doesn't exist at the moment start() is
1331 called, it will be created. If it cannot be created, the starting
1334 If the file exists and \a mode is QIODevice::Truncate, the file
1335 will be truncated. Otherwise (if \a mode is QIODevice::Append),
1336 the file will be appended to.
1338 Calling setStandardOutputFile() after the process has started has
1341 \sa setStandardInputFile(), setStandardErrorFile(),
1342 setStandardOutputProcess()
1344 void QProcess::setStandardOutputFile(const QString &fileName, OpenMode mode)
1346 Q_ASSERT(mode == Append || mode == Truncate);
1349 d->stdoutChannel = fileName;
1350 d->stdoutChannel.append = mode == Append;
1356 Redirects the process' standard error to the file \a
1357 fileName. When the redirection is in place, the standard error
1358 read channel is closed: reading from it using read() will always
1359 fail, as will readAllStandardError(). The file will be appended to
1360 if \a mode is Append, otherwise, it will be truncated.
1362 See setStandardOutputFile() for more information on how the file
1365 Note: if setProcessChannelMode() was called with an argument of
1366 QProcess::MergedChannels, this function has no effect.
1368 \sa setStandardInputFile(), setStandardOutputFile(),
1369 setStandardOutputProcess()
1371 void QProcess::setStandardErrorFile(const QString &fileName, OpenMode mode)
1373 Q_ASSERT(mode == Append || mode == Truncate);
1376 d->stderrChannel = fileName;
1377 d->stderrChannel.append = mode == Append;
1383 Pipes the standard output stream of this process to the \a
1384 destination process' standard input.
1386 The following shell command:
1387 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 2
1389 Can be accomplished with QProcesses with the following code:
1390 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 3
1392 void QProcess::setStandardOutputProcess(QProcess *destination)
1394 QProcessPrivate *dfrom = d_func();
1395 QProcessPrivate *dto = destination->d_func();
1396 dfrom->stdoutChannel.pipeTo(dto);
1397 dto->stdinChannel.pipeFrom(dfrom);
1400 #if defined(Q_OS_WIN) || defined(Q_OS_SYMBIAN)
1405 Returns the additional native command line arguments for the program.
1407 \note This function is available only on the Windows and Symbian
1410 \sa setNativeArguments()
1412 QString QProcess::nativeArguments() const
1414 Q_D(const QProcess);
1415 return d->nativeArguments;
1422 Sets additional native command line \a arguments for the program.
1424 On operating systems where the system API for passing command line
1425 \a arguments to a subprocess natively uses a single string, one can
1426 conceive command lines which cannot be passed via QProcess's portable
1427 list-based API. In such cases this function must be used to set a
1428 string which is \e appended to the string composed from the usual
1429 argument list, with a delimiting space.
1431 \note This function is available only on the Windows and Symbian
1434 \sa nativeArguments()
1436 void QProcess::setNativeArguments(const QString &arguments)
1439 d->nativeArguments = arguments;
1445 If QProcess has been assigned a working directory, this function returns
1446 the working directory that the QProcess will enter before the program has
1447 started. Otherwise, (i.e., no directory has been assigned,) an empty
1448 string is returned, and QProcess will use the application's current
1449 working directory instead.
1451 \sa setWorkingDirectory()
1453 QString QProcess::workingDirectory() const
1455 Q_D(const QProcess);
1456 return d->workingDirectory;
1460 Sets the working directory to \a dir. QProcess will start the
1461 process in this directory. The default behavior is to start the
1462 process in the working directory of the calling process.
1464 \note The working directory setting is ignored on Symbian;
1465 the private directory of the process is considered its working
1468 \sa workingDirectory(), start()
1470 void QProcess::setWorkingDirectory(const QString &dir)
1473 d->workingDirectory = dir;
1477 Returns the native process identifier for the running process, if
1478 available. If no process is currently running, 0 is returned.
1480 Q_PID QProcess::pid() const
1482 Q_D(const QProcess);
1488 This function operates on the current read channel.
1490 \sa readChannel(), setReadChannel()
1492 bool QProcess::canReadLine() const
1494 Q_D(const QProcess);
1495 const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1496 ? &d->errorReadBuffer
1497 : &d->outputReadBuffer;
1498 return readBuffer->canReadLine() || QIODevice::canReadLine();
1502 Closes all communication with the process and kills it. After calling this
1503 function, QProcess will no longer emit readyRead(), and data can no
1504 longer be read or written.
1506 void QProcess::close()
1508 emit aboutToClose();
1509 while (waitForBytesWritten(-1))
1512 waitForFinished(-1);
1518 Returns true if the process is not running, and no more data is available
1519 for reading; otherwise returns false.
1521 bool QProcess::atEnd() const
1523 Q_D(const QProcess);
1524 const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1525 ? &d->errorReadBuffer
1526 : &d->outputReadBuffer;
1527 return QIODevice::atEnd() && (!isOpen() || readBuffer->isEmpty());
1532 bool QProcess::isSequential() const
1539 qint64 QProcess::bytesAvailable() const
1541 Q_D(const QProcess);
1542 const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1543 ? &d->errorReadBuffer
1544 : &d->outputReadBuffer;
1545 #if defined QPROCESS_DEBUG
1546 qDebug("QProcess::bytesAvailable() == %i (%s)", readBuffer->size(),
1547 (d->processChannel == QProcess::StandardError) ? "stderr" : "stdout");
1549 return readBuffer->size() + QIODevice::bytesAvailable();
1554 qint64 QProcess::bytesToWrite() const
1556 Q_D(const QProcess);
1557 qint64 size = d->writeBuffer.size();
1559 size += d->pipeWriterBytesToWrite();
1565 Returns the type of error that occurred last.
1569 QProcess::ProcessError QProcess::error() const
1571 Q_D(const QProcess);
1572 return d->processError;
1576 Returns the current state of the process.
1578 \sa stateChanged(), error()
1580 QProcess::ProcessState QProcess::state() const
1582 Q_D(const QProcess);
1583 return d->processState;
1588 Sets the environment that QProcess will use when starting a process to the
1589 \a environment specified which consists of a list of key=value pairs.
1591 For example, the following code adds the \c{C:\\BIN} directory to the list of
1592 executable paths (\c{PATHS}) on Windows:
1594 \snippet doc/src/snippets/qprocess-environment/main.cpp 0
1596 \note This function is less efficient than the setProcessEnvironment()
1599 \sa environment(), setProcessEnvironment(), systemEnvironment()
1601 void QProcess::setEnvironment(const QStringList &environment)
1603 setProcessEnvironment(QProcessEnvironmentPrivate::fromList(environment));
1608 Returns the environment that QProcess will use when starting a
1609 process, or an empty QStringList if no environment has been set
1610 using setEnvironment() or setEnvironmentHash(). If no environment
1611 has been set, the environment of the calling process will be used.
1613 \note The environment settings are ignored on Windows CE and Symbian,
1614 as there is no concept of an environment.
1616 \sa processEnvironment(), setEnvironment(), systemEnvironment()
1618 QStringList QProcess::environment() const
1620 Q_D(const QProcess);
1621 return d->environment.toStringList();
1626 Sets the environment that QProcess will use when starting a process to the
1627 \a environment object.
1629 For example, the following code adds the \c{C:\\BIN} directory to the list of
1630 executable paths (\c{PATHS}) on Windows and sets \c{TMPDIR}:
1632 \snippet doc/src/snippets/qprocess-environment/main.cpp 1
1634 Note how, on Windows, environment variable names are case-insensitive.
1636 \sa processEnvironment(), QProcessEnvironment::systemEnvironment(), setEnvironment()
1638 void QProcess::setProcessEnvironment(const QProcessEnvironment &environment)
1641 d->environment = environment;
1646 Returns the environment that QProcess will use when starting a
1647 process, or an empty object if no environment has been set using
1648 setEnvironment() or setProcessEnvironment(). If no environment has
1649 been set, the environment of the calling process will be used.
1651 \note The environment settings are ignored on Windows CE,
1652 as there is no concept of an environment.
1654 \sa setProcessEnvironment(), setEnvironment(), QProcessEnvironment::isEmpty()
1656 QProcessEnvironment QProcess::processEnvironment() const
1658 Q_D(const QProcess);
1659 return d->environment;
1663 Blocks until the process has started and the started() signal has
1664 been emitted, or until \a msecs milliseconds have passed.
1666 Returns true if the process was started successfully; otherwise
1667 returns false (if the operation timed out or if an error
1670 This function can operate without an event loop. It is
1671 useful when writing non-GUI applications and when performing
1672 I/O operations in a non-GUI thread.
1674 \warning Calling this function from the main (GUI) thread
1675 might cause your user interface to freeze.
1677 If msecs is -1, this function will not time out.
1679 \sa started(), waitForReadyRead(), waitForBytesWritten(), waitForFinished()
1681 bool QProcess::waitForStarted(int msecs)
1684 if (d->processState == QProcess::Running)
1687 return d->waitForStarted(msecs);
1692 bool QProcess::waitForReadyRead(int msecs)
1696 if (d->processState == QProcess::NotRunning)
1698 if (d->processChannel == QProcess::StandardOutput && d->stdoutChannel.closed)
1700 if (d->processChannel == QProcess::StandardError && d->stderrChannel.closed)
1702 return d->waitForReadyRead(msecs);
1707 bool QProcess::waitForBytesWritten(int msecs)
1710 if (d->processState == QProcess::NotRunning)
1712 if (d->processState == QProcess::Starting) {
1713 QElapsedTimer stopWatch;
1715 bool started = waitForStarted(msecs);
1719 msecs -= stopWatch.elapsed();
1722 return d->waitForBytesWritten(msecs);
1726 Blocks until the process has finished and the finished() signal
1727 has been emitted, or until \a msecs milliseconds have passed.
1729 Returns true if the process finished; otherwise returns false (if
1730 the operation timed out, if an error occurred, or if this QProcess
1731 is already finished).
1733 This function can operate without an event loop. It is
1734 useful when writing non-GUI applications and when performing
1735 I/O operations in a non-GUI thread.
1737 \warning Calling this function from the main (GUI) thread
1738 might cause your user interface to freeze.
1740 If msecs is -1, this function will not time out.
1742 \sa finished(), waitForStarted(), waitForReadyRead(), waitForBytesWritten()
1744 bool QProcess::waitForFinished(int msecs)
1747 if (d->processState == QProcess::NotRunning)
1749 if (d->processState == QProcess::Starting) {
1750 QElapsedTimer stopWatch;
1752 bool started = waitForStarted(msecs);
1756 msecs -= stopWatch.elapsed();
1759 return d->waitForFinished(msecs);
1763 Sets the current state of the QProcess to the \a state specified.
1767 void QProcess::setProcessState(ProcessState state)
1770 if (d->processState == state)
1772 d->processState = state;
1773 emit stateChanged(state);
1777 This function is called in the child process context just before the
1778 program is executed on Unix or Mac OS X (i.e., after \e fork(), but before
1779 \e execve()). Reimplement this function to do last minute initialization
1780 of the child process. Example:
1782 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 4
1784 You cannot exit the process (by calling exit(), for instance) from
1785 this function. If you need to stop the program before it starts
1786 execution, your workaround is to emit finished() and then call
1789 \warning This function is called by QProcess on Unix and Mac OS X
1790 only. On Windows, it is not called.
1792 void QProcess::setupChildProcess()
1798 qint64 QProcess::readData(char *data, qint64 maxlen)
1801 QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1802 ? &d->errorReadBuffer
1803 : &d->outputReadBuffer;
1805 if (maxlen == 1 && !readBuffer->isEmpty()) {
1806 int c = readBuffer->getChar();
1808 #if defined QPROCESS_DEBUG
1809 qDebug("QProcess::readData(%p \"%s\", %d) == -1",
1810 data, qt_prettyDebug(data, 1, maxlen).constData(), 1);
1815 #if defined QPROCESS_DEBUG
1816 qDebug("QProcess::readData(%p \"%s\", %d) == 1",
1817 data, qt_prettyDebug(data, 1, maxlen).constData(), 1);
1822 qint64 bytesToRead = qint64(qMin(readBuffer->size(), (int)maxlen));
1823 qint64 readSoFar = 0;
1824 while (readSoFar < bytesToRead) {
1825 const char *ptr = readBuffer->readPointer();
1826 int bytesToReadFromThisBlock = qMin<qint64>(bytesToRead - readSoFar,
1827 readBuffer->nextDataBlockSize());
1828 memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
1829 readSoFar += bytesToReadFromThisBlock;
1830 readBuffer->free(bytesToReadFromThisBlock);
1833 #if defined QPROCESS_DEBUG
1834 qDebug("QProcess::readData(%p \"%s\", %lld) == %lld",
1835 data, qt_prettyDebug(data, readSoFar, 16).constData(), maxlen, readSoFar);
1837 if (!readSoFar && d->processState == QProcess::NotRunning)
1844 qint64 QProcess::writeData(const char *data, qint64 len)
1848 #if defined(Q_OS_WINCE)
1851 d->processError = QProcess::WriteError;
1852 setErrorString(tr("Error writing to process"));
1853 emit error(d->processError);
1857 if (d->stdinChannel.closed) {
1858 #if defined QPROCESS_DEBUG
1859 qDebug("QProcess::writeData(%p \"%s\", %lld) == 0 (write channel closing)",
1860 data, qt_prettyDebug(data, len, 16).constData(), len);
1866 d->writeBuffer.putChar(*data);
1867 if (d->stdinChannel.notifier)
1868 d->stdinChannel.notifier->setEnabled(true);
1869 #if defined QPROCESS_DEBUG
1870 qDebug("QProcess::writeData(%p \"%s\", %lld) == 1 (written to buffer)",
1871 data, qt_prettyDebug(data, len, 16).constData(), len);
1876 char *dest = d->writeBuffer.reserve(len);
1877 memcpy(dest, data, len);
1878 if (d->stdinChannel.notifier)
1879 d->stdinChannel.notifier->setEnabled(true);
1880 #if defined QPROCESS_DEBUG
1881 qDebug("QProcess::writeData(%p \"%s\", %lld) == %lld (written to buffer)",
1882 data, qt_prettyDebug(data, len, 16).constData(), len, len);
1888 Regardless of the current read channel, this function returns all
1889 data available from the standard output of the process as a
1892 \sa readyReadStandardOutput(), readAllStandardError(), readChannel(), setReadChannel()
1894 QByteArray QProcess::readAllStandardOutput()
1896 ProcessChannel tmp = readChannel();
1897 setReadChannel(StandardOutput);
1898 QByteArray data = readAll();
1899 setReadChannel(tmp);
1904 Regardless of the current read channel, this function returns all
1905 data available from the standard error of the process as a
1908 \sa readyReadStandardError(), readAllStandardOutput(), readChannel(), setReadChannel()
1910 QByteArray QProcess::readAllStandardError()
1912 ProcessChannel tmp = readChannel();
1913 setReadChannel(StandardError);
1914 QByteArray data = readAll();
1915 setReadChannel(tmp);
1920 Starts the given \a program in a new process, if none is already
1921 running, passing the command line arguments in \a arguments. The OpenMode
1924 The QProcess object will immediately enter the Starting state. If the
1925 process starts successfully, QProcess will emit started(); otherwise,
1926 error() will be emitted. If the QProcess object is already running a
1927 process, a warning may be printed at the console, and the existing
1928 process will continue running.
1930 \note Processes are started asynchronously, which means the started()
1931 and error() signals may be delayed. Call waitForStarted() to make
1932 sure the process has started (or has failed to start) and those signals
1935 \note No further splitting of the arguments is performed.
1937 \bold{Windows:} Arguments that contain spaces are wrapped in quotes.
1939 \sa pid(), started(), waitForStarted()
1941 void QProcess::start(const QString &program, const QStringList &arguments, OpenMode mode)
1944 if (d->processState != NotRunning) {
1945 qWarning("QProcess::start: Process is already running");
1949 #if defined QPROCESS_DEBUG
1950 qDebug() << "QProcess::start(" << program << ',' << arguments << ',' << mode << ')';
1953 d->outputReadBuffer.clear();
1954 d->errorReadBuffer.clear();
1956 if (d->stdinChannel.type != QProcessPrivate::Channel::Normal)
1957 mode &= ~WriteOnly; // not open for writing
1958 if (d->stdoutChannel.type != QProcessPrivate::Channel::Normal &&
1959 (d->stderrChannel.type != QProcessPrivate::Channel::Normal ||
1960 d->processChannelMode == MergedChannels))
1961 mode &= ~ReadOnly; // not open for reading
1964 QIODevice::open(mode);
1966 d->stdinChannel.closed = false;
1967 d->stdoutChannel.closed = false;
1968 d->stderrChannel.closed = false;
1970 d->program = program;
1971 d->arguments = arguments;
1974 d->exitStatus = NormalExit;
1975 d->processError = QProcess::UnknownError;
1976 d->errorString.clear();
1981 static QStringList parseCombinedArgString(const QString &program)
1986 bool inQuote = false;
1988 // handle quoting. tokens can be surrounded by double quotes
1989 // "hello world". three consecutive double quotes represent
1990 // the quote character itself.
1991 for (int i = 0; i < program.size(); ++i) {
1992 if (program.at(i) == QLatin1Char('"')) {
1994 if (quoteCount == 3) {
1995 // third consecutive quote
1997 tmp += program.at(i);
2002 if (quoteCount == 1)
2006 if (!inQuote && program.at(i).isSpace()) {
2007 if (!tmp.isEmpty()) {
2012 tmp += program.at(i);
2024 Starts the program \a program in a new process, if one is not already
2025 running. \a program is a single string of text containing both the
2026 program name and its arguments. The arguments are separated by one or
2027 more spaces. For example:
2029 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 5
2031 The \a program string can also contain quotes, to ensure that arguments
2032 containing spaces are correctly supplied to the new process. For example:
2034 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 6
2036 If the QProcess object is already running a process, a warning may be
2037 printed at the console, and the existing process will continue running.
2039 Note that, on Windows, quotes need to be both escaped and quoted.
2040 For example, the above code would be specified in the following
2041 way to ensure that \c{"My Documents"} is used as the argument to
2042 the \c dir executable:
2044 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 7
2046 The OpenMode is set to \a mode.
2048 void QProcess::start(const QString &program, OpenMode mode)
2050 QStringList args = parseCombinedArgString(program);
2051 if (args.isEmpty()) {
2053 d->processError = QProcess::FailedToStart;
2054 setErrorString(tr("No program defined"));
2055 emit error(d->processError);
2059 QString prog = args.first();
2062 start(prog, args, mode);
2066 Attempts to terminate the process.
2068 The process may not exit as a result of calling this function (it is given
2069 the chance to prompt the user for any unsaved files, etc).
2071 On Windows, terminate() posts a WM_CLOSE message to all toplevel windows
2072 of the process and then to the main thread of the process itself. On Unix
2073 and Mac OS X the SIGTERM signal is sent.
2075 Console applications on Windows that do not run an event loop, or whose
2076 event loop does not handle the WM_CLOSE message, can only be terminated by
2079 On Symbian, this function requires platform security capability
2080 \c PowerMgmt. If absent, the process will panic with KERN-EXEC 46.
2082 \note Terminating running processes from other processes will typically
2083 cause a panic in Symbian due to platform security.
2085 \sa {Symbian Platform Security Requirements}
2088 void QProcess::terminate()
2091 d->terminateProcess();
2095 Kills the current process, causing it to exit immediately.
2097 On Windows, kill() uses TerminateProcess, and on Unix and Mac OS X, the
2098 SIGKILL signal is sent to the process.
2100 On Symbian, this function requires platform security capability
2101 \c PowerMgmt. If absent, the process will panic with KERN-EXEC 46.
2103 \note Killing running processes from other processes will typically
2104 cause a panic in Symbian due to platform security.
2106 \sa {Symbian Platform Security Requirements}
2109 void QProcess::kill()
2116 Returns the exit code of the last process that finished.
2118 int QProcess::exitCode() const
2120 Q_D(const QProcess);
2127 Returns the exit status of the last process that finished.
2129 On Windows, if the process was terminated with TerminateProcess()
2130 from another application this function will still return NormalExit
2131 unless the exit code is less than 0.
2133 QProcess::ExitStatus QProcess::exitStatus() const
2135 Q_D(const QProcess);
2136 return d->exitStatus;
2140 Starts the program \a program with the arguments \a arguments in a
2141 new process, waits for it to finish, and then returns the exit
2142 code of the process. Any data the new process writes to the
2143 console is forwarded to the calling process.
2145 The environment and working directory are inherited from the calling
2148 On Windows, arguments that contain spaces are wrapped in quotes.
2150 If the process cannot be started, -2 is returned. If the process
2151 crashes, -1 is returned. Otherwise, the process' exit code is
2154 int QProcess::execute(const QString &program, const QStringList &arguments)
2157 process.setReadChannelMode(ForwardedChannels);
2158 process.start(program, arguments);
2159 if (!process.waitForFinished(-1))
2161 return process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;
2167 Starts the program \a program in a new process. \a program is a
2168 single string of text containing both the program name and its
2169 arguments. The arguments are separated by one or more spaces.
2171 int QProcess::execute(const QString &program)
2174 process.setReadChannelMode(ForwardedChannels);
2175 process.start(program);
2176 if (!process.waitForFinished(-1))
2178 return process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;
2182 Starts the program \a program with the arguments \a arguments in a
2183 new process, and detaches from it. Returns true on success;
2184 otherwise returns false. If the calling process exits, the
2185 detached process will continue to live.
2187 Note that arguments that contain spaces are not passed to the
2188 process as separate arguments.
2190 \bold{Unix:} The started process will run in its own session and act
2193 \bold{Windows:} Arguments that contain spaces are wrapped in quotes.
2194 The started process will run as a regular standalone process.
2196 The process will be started in the directory \a workingDirectory.
2198 If the function is successful then *\a pid is set to the process
2199 identifier of the started process.
2201 bool QProcess::startDetached(const QString &program,
2202 const QStringList &arguments,
2203 const QString &workingDirectory,
2206 return QProcessPrivate::startDetached(program,
2213 Starts the program \a program with the given \a arguments in a
2214 new process, and detaches from it. Returns true on success;
2215 otherwise returns false. If the calling process exits, the
2216 detached process will continue to live.
2218 \note Arguments that contain spaces are not passed to the
2219 process as separate arguments.
2221 \bold{Unix:} The started process will run in its own session and act
2224 \bold{Windows:} Arguments that contain spaces are wrapped in quotes.
2225 The started process will run as a regular standalone process.
2227 bool QProcess::startDetached(const QString &program,
2228 const QStringList &arguments)
2230 return QProcessPrivate::startDetached(program, arguments);
2236 Starts the program \a program in a new process. \a program is a
2237 single string of text containing both the program name and its
2238 arguments. The arguments are separated by one or more spaces.
2240 The \a program string can also contain quotes, to ensure that arguments
2241 containing spaces are correctly supplied to the new process.
2243 bool QProcess::startDetached(const QString &program)
2245 QStringList args = parseCombinedArgString(program);
2249 QString prog = args.first();
2252 return QProcessPrivate::startDetached(prog, args);
2255 QT_BEGIN_INCLUDE_NAMESPACE
2256 #if defined(Q_OS_MAC) && !defined(QT_NO_CORESERVICES)
2257 # include <crt_externs.h>
2258 # define environ (*_NSGetEnviron())
2259 #elif defined(Q_OS_WINCE) || defined(Q_OS_SYMBIAN) || (defined(Q_OS_MAC) && defined(QT_NO_CORESERVICES))
2260 static char *qt_empty_environ[] = { 0 };
2261 #define environ qt_empty_environ
2262 #elif !defined(Q_OS_WIN)
2263 extern char **environ;
2265 QT_END_INCLUDE_NAMESPACE
2270 Returns the environment of the calling process as a list of
2271 key=value pairs. Example:
2273 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 8
2275 This function does not cache the system environment. Therefore, it's
2276 possible to obtain an updated version of the environment if low-level C
2277 library functions like \tt setenv ot \tt putenv have been called.
2279 However, note that repeated calls to this function will recreate the
2280 list of environment variables, which is a non-trivial operation.
2282 \note For new code, it is recommended to use QProcessEnvironment::systemEnvironment()
2284 \sa QProcessEnvironment::systemEnvironment(), environment(), setEnvironment()
2286 QStringList QProcess::systemEnvironment()
2291 while ((entry = environ[count++]))
2292 tmp << QString::fromLocal8Bit(entry);
2297 \fn QProcessEnvironment QProcessEnvironment::systemEnvironment()
2301 \brief The systemEnvironment function returns the environment of
2302 the calling process.
2304 It is returned as a QProcessEnvironment. This function does not
2305 cache the system environment. Therefore, it's possible to obtain
2306 an updated version of the environment if low-level C library
2307 functions like \tt setenv ot \tt putenv have been called.
2309 However, note that repeated calls to this function will recreate the
2310 QProcessEnvironment object, which is a non-trivial operation.
2312 \sa QProcess::systemEnvironment()
2319 Typedef for the identifiers used to represent processes on the underlying
2320 platform. On Unix and Symbian, this corresponds to \l qint64; on Windows, it
2321 corresponds to \c{_PROCESS_INFORMATION*}.
2328 #include "moc_qprocess.cpp"
2330 #endif // QT_NO_PROCESS