source: trunk/src/corelib/io/qprocess.cpp@ 76

Last change on this file since 76 was 72, checked in by Dmitry A. Kuminov, 16 years ago

corelib: OS/2: Reimplemented QProcess using libc pipes (#7).

File size: 53.1 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4** Contact: Qt Software Information ([email protected])
5**
6** This file is part of the QtCore module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial Usage
10** Licensees holding valid Qt Commercial licenses may use this file in
11** accordance with the Qt Commercial License Agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and Nokia.
14**
15** GNU Lesser General Public License Usage
16** Alternatively, this file may be used under the terms of the GNU Lesser
17** General Public License version 2.1 as published by the Free Software
18** Foundation and appearing in the file LICENSE.LGPL included in the
19** packaging of this file. Please review the following information to
20** ensure the GNU Lesser General Public License version 2.1 requirements
21** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
22**
23** In addition, as a special exception, Nokia gives you certain
24** additional rights. These rights are described in the Nokia Qt LGPL
25** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
26** package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you are unsure which license is appropriate for your use, please
37** contact the sales department at [email protected].
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
52QT_BEGIN_NAMESPACE
53/*
54 Returns a human readable representation of the first \a len
55 characters in \a data.
56*/
57static 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
83QT_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#ifndef QT_NO_PROCESS
101
102QT_BEGIN_NAMESPACE
103
104void QProcessPrivate::Channel::clear()
105{
106 switch (type) {
107 case PipeSource:
108 Q_ASSERT(process);
109 process->stdinChannel.type = Normal;
110 process->stdinChannel.process = 0;
111 break;
112 case PipeSink:
113 Q_ASSERT(process);
114 process->stdoutChannel.type = Normal;
115 process->stdoutChannel.process = 0;
116 break;
117 }
118
119 type = Normal;
120 file.clear();
121 process = 0;
122}
123
124/*!
125 \class QProcess
126
127 \brief The QProcess class is used to start external programs and
128 to communicate with them.
129
130 \ingroup io
131 \ingroup misc
132 \mainclass
133 \reentrant
134
135 To start a process, pass the name and command line arguments of
136 the program you want to run as arguments to start(). For example:
137
138 \snippet doc/src/snippets/qprocess/qprocess-simpleexecution.cpp 0
139 \dots
140 \snippet doc/src/snippets/qprocess/qprocess-simpleexecution.cpp 1
141 \snippet doc/src/snippets/qprocess/qprocess-simpleexecution.cpp 2
142
143 QProcess then enters the \l Starting state, and when the program
144 has started, QProcess enters the \l Running state and emits
145 started().
146
147 QProcess allows you to treat a process as a sequential I/O
148 device. You can write to and read from the process just as you
149 would access a network connection using QTcpSocket. You can then
150 write to the process's standard input by calling write(), and
151 read the standard output by calling read(), readLine(), and
152 getChar(). Because it inherits QIODevice, QProcess can also be
153 used as an input source for QXmlReader, or for generating data to
154 be uploaded using QFtp.
155
156 \note On Windows CE, reading and writing to a process is not supported.
157
158 When the process exits, QProcess reenters the \l NotRunning state
159 (the initial state), and emits finished().
160
161 The finished() signal provides the exit code and exit status of
162 the process as arguments, and you can also call exitCode() to
163 obtain the exit code of the last process that finished, and
164 exitStatus() to obtain its exit status. If an error occurs at
165 any point in time, QProcess will emit the error() signal. You
166 can also call error() to find the type of error that occurred
167 last, and state() to find the current process state.
168
169 \section1 Communicating via Channels
170
171 Processes have two predefined output channels: The standard
172 output channel (\c stdout) supplies regular console output, and
173 the standard error channel (\c stderr) usually supplies the
174 errors that are printed by the process. These channels represent
175 two separate streams of data. You can toggle between them by
176 calling setReadChannel(). QProcess emits readyRead() when data is
177 available on the current read channel. It also emits
178 readyReadStandardOutput() when new standard output data is
179 available, and when new standard error data is available,
180 readyReadStandardError() is emitted. Instead of calling read(),
181 readLine(), or getChar(), you can explicitly read all data from
182 either of the two channels by calling readAllStandardOutput() or
183 readAllStandardError().
184
185 The terminology for the channels can be misleading. Be aware that
186 the process's output channels correspond to QProcess's
187 \e read channels, whereas the process's input channels correspond
188 to QProcess's \e write channels. This is because what we read
189 using QProcess is the process's output, and what we write becomes
190 the process's input.
191
192 QProcess can merge the two output channels, so that standard
193 output and standard error data from the running process both use
194 the standard output channel. Call setProcessChannelMode() with
195 MergedChannels before starting the process to activative
196 this feature. You also have the option of forwarding the output of
197 the running process to the calling, main process, by passing
198 ForwardedChannels as the argument.
199
200 Certain processes need special environment settings in order to
201 operate. You can set environment variables for your process by
202 calling setEnvironment(). To set a working directory, call
203 setWorkingDirectory(). By default, processes are run in the
204 current working directory of the calling process.
205
206 \section1 Synchronous Process API
207
208 QProcess provides a set of functions which allow it to be used
209 without an event loop, by suspending the calling thread until
210 certain signals are emitted:
211
212 \list
213 \o waitForStarted() blocks until the process has started.
214
215 \o waitForReadyRead() blocks until new data is
216 available for reading on the current read channel.
217
218 \o waitForBytesWritten() blocks until one payload of
219 data has been written to the process.
220
221 \o waitForFinished() blocks until the process has finished.
222 \endlist
223
224 Calling these functions from the main thread (the thread that
225 calls QApplication::exec()) may cause your user interface to
226 freeze.
227
228 The following example runs \c gzip to compress the string "Qt
229 rocks!", without an event loop:
230
231 \snippet doc/src/snippets/process/process.cpp 0
232
233 \section1 Notes for Windows and OS/2 Users
234
235 Some Windows and OS/2 commands (for example, \c dir) are not provided
236 by separate applications, but by the command interpreter itself.
237 If you attempt to use QProcess to execute these commands directly,
238 it won't work. One possible solution is to execute the command
239 interpreter itself (\c{cmd.exe} on some Windows systems), and ask
240 the interpreter to execute the desired command.
241
242 \sa QBuffer, QFile, QTcpSocket
243*/
244
245/*!
246 \enum QProcess::ProcessChannel
247
248 This enum describes the process channels used by the running process.
249 Pass one of these values to setReadChannel() to set the
250 current read channel of QProcess.
251
252 \value StandardOutput The standard output (stdout) of the running
253 process.
254
255 \value StandardError The standard error (stderr) of the running
256 process.
257
258 \sa setReadChannel()
259*/
260
261/*!
262 \enum QProcess::ProcessChannelMode
263
264 This enum describes the process channel modes of QProcess. Pass
265 one of these values to setProcessChannelMode() to set the
266 current read channel mode.
267
268 \value SeparateChannels QProcess manages the output of the
269 running process, keeping standard output and standard error data
270 in separate internal buffers. You can select the QProcess's
271 current read channel by calling setReadChannel(). This is the
272 default channel mode of QProcess.
273
274 \value MergedChannels QProcess merges the output of the running
275 process into the standard output channel (\c stdout). The
276 standard error channel (\c stderr) will not receive any data. The
277 standard output and standard error data of the running process
278 are interleaved.
279
280 \value ForwardedChannels QProcess forwards the output of the
281 running process onto the main process. Anything the child process
282 writes to its standard output and standard error will be written
283 to the standard output and standard error of the main process.
284
285 \sa setReadChannelMode()
286*/
287
288/*!
289 \enum QProcess::ProcessError
290
291 This enum describes the different types of errors that are
292 reported by QProcess.
293
294 \value FailedToStart The process failed to start. Either the
295 invoked program is missing, or you may have insufficient
296 permissions to invoke the program.
297
298 \value Crashed The process crashed some time after starting
299 successfully.
300
301 \value Timedout The last waitFor...() function timed out. The
302 state of QProcess is unchanged, and you can try calling
303 waitFor...() again.
304
305 \value WriteError An error occurred when attempting to write to the
306 process. For example, the process may not be running, or it may
307 have closed its input channel.
308
309 \value ReadError An error occurred when attempting to read from
310 the process. For example, the process may not be running.
311
312 \value UnknownError An unknown error occurred. This is the default
313 return value of error().
314
315 \sa error()
316*/
317
318/*!
319 \enum QProcess::ProcessState
320
321 This enum describes the different states of QProcess.
322
323 \value NotRunning The process is not running.
324
325 \value Starting The process is starting, but the program has not
326 yet been invoked.
327
328 \value Running The process is running and is ready for reading and
329 writing.
330
331 \sa state()
332*/
333
334/*!
335 \enum QProcess::ExitStatus
336
337 This enum describes the different exit statuses of QProcess.
338
339 \value NormalExit The process exited normally.
340
341 \value CrashExit The process crashed.
342
343 \sa exitStatus()
344*/
345
346/*!
347 \fn void QProcess::error(QProcess::ProcessError error)
348
349 This signal is emitted when an error occurs with the process. The
350 specified \a error describes the type of error that occurred.
351*/
352
353/*!
354 \fn void QProcess::started()
355
356 This signal is emitted by QProcess when the process has started,
357 and state() returns \l Running.
358*/
359
360/*!
361 \fn void QProcess::stateChanged(QProcess::ProcessState newState)
362
363 This signal is emitted whenever the state of QProcess changes. The
364 \a newState argument is the state QProcess changed to.
365*/
366
367/*!
368 \fn void QProcess::finished(int exitCode)
369 \obsolete
370 \overload
371
372 Use finished(int exitCode, QProcess::ExitStatus status) instead.
373*/
374
375/*!
376 \fn void QProcess::finished(int exitCode, QProcess::ExitStatus exitStatus)
377
378 This signal is emitted when the process finishes. \a exitCode is the exit
379 code of the process, and \a exitStatus is the exit status. After the
380 process has finished, the buffers in QProcess are still intact. You can
381 still read any data that the process may have written before it finished.
382
383 \sa exitStatus()
384*/
385
386/*!
387 \fn void QProcess::readyReadStandardOutput()
388
389 This signal is emitted when the process has made new data
390 available through its standard output channel (\c stdout). It is
391 emitted regardless of the current \l{readChannel()}{read channel}.
392
393 \sa readAllStandardOutput(), readChannel()
394*/
395
396/*!
397 \fn void QProcess::readyReadStandardError()
398
399 This signal is emitted when the process has made new data
400 available through its standard error channel (\c stderr). It is
401 emitted regardless of the current \l{readChannel()}{read
402 channel}.
403
404 \sa readAllStandardError(), readChannel()
405*/
406
407/*! \internal
408*/
409QProcessPrivate::QProcessPrivate()
410{
411 processChannel = QProcess::StandardOutput;
412 processChannelMode = QProcess::SeparateChannels;
413 processError = QProcess::UnknownError;
414 processState = QProcess::NotRunning;
415 pid = 0;
416 sequenceNumber = 0;
417 exitCode = 0;
418 exitStatus = QProcess::NormalExit;
419 startupSocketNotifier = 0;
420 deathNotifier = 0;
421 notifier = 0;
422 pipeWriter = 0;
423 childStartedPipe[0] = INVALID_Q_PIPE;
424 childStartedPipe[1] = INVALID_Q_PIPE;
425 deathPipe[0] = INVALID_Q_PIPE;
426 deathPipe[1] = INVALID_Q_PIPE;
427 exitCode = 0;
428 crashed = false;
429 dying = false;
430 emittedReadyRead = false;
431 emittedBytesWritten = false;
432#ifdef Q_WS_WIN
433 pipeWriter = 0;
434 processFinishedNotifier = 0;
435#endif // Q_WS_WIN
436#ifdef Q_OS_UNIX
437 serial = 0;
438#endif
439}
440
441/*! \internal
442*/
443QProcessPrivate::~QProcessPrivate()
444{
445 if (stdinChannel.process)
446 stdinChannel.process->stdoutChannel.clear();
447 if (stdoutChannel.process)
448 stdoutChannel.process->stdinChannel.clear();
449}
450
451/*! \internal
452*/
453void QProcessPrivate::cleanup()
454{
455 q_func()->setProcessState(QProcess::NotRunning);
456#ifdef Q_OS_WIN
457 if (pid) {
458 CloseHandle(pid->hThread);
459 CloseHandle(pid->hProcess);
460 delete pid;
461 pid = 0;
462 }
463 if (processFinishedNotifier) {
464 processFinishedNotifier->setEnabled(false);
465 qDeleteInEventHandler(processFinishedNotifier);
466 processFinishedNotifier = 0;
467 }
468
469#endif
470 pid = 0;
471 sequenceNumber = 0;
472 dying = false;
473
474 if (stdoutChannel.notifier) {
475 stdoutChannel.notifier->setEnabled(false);
476 qDeleteInEventHandler(stdoutChannel.notifier);
477 stdoutChannel.notifier = 0;
478 }
479 if (stderrChannel.notifier) {
480 stderrChannel.notifier->setEnabled(false);
481 qDeleteInEventHandler(stderrChannel.notifier);
482 stderrChannel.notifier = 0;
483 }
484 if (stdinChannel.notifier) {
485 stdinChannel.notifier->setEnabled(false);
486 qDeleteInEventHandler(stdinChannel.notifier);
487 stdinChannel.notifier = 0;
488 }
489 if (startupSocketNotifier) {
490 startupSocketNotifier->setEnabled(false);
491 qDeleteInEventHandler(startupSocketNotifier);
492 startupSocketNotifier = 0;
493 }
494 if (deathNotifier) {
495 deathNotifier->setEnabled(false);
496 qDeleteInEventHandler(deathNotifier);
497 deathNotifier = 0;
498 }
499 if (notifier) {
500 qDeleteInEventHandler(notifier);
501 notifier = 0;
502 }
503 destroyPipe(stdoutChannel.pipe);
504 destroyPipe(stderrChannel.pipe);
505 destroyPipe(stdinChannel.pipe);
506 destroyPipe(childStartedPipe);
507 destroyPipe(deathPipe);
508#ifdef Q_OS_UNIX
509 serial = 0;
510#endif
511}
512
513/*! \internal
514*/
515bool QProcessPrivate::_q_canReadStandardOutput()
516{
517 Q_Q(QProcess);
518 qint64 available = bytesAvailableFromStdout();
519 if (available == 0) {
520 if (stdoutChannel.notifier)
521 stdoutChannel.notifier->setEnabled(false);
522 destroyPipe(stdoutChannel.pipe);
523#if defined QPROCESS_DEBUG
524 qDebug("QProcessPrivate::canReadStandardOutput(), 0 bytes available");
525#endif
526 return false;
527 }
528
529 char *ptr = outputReadBuffer.reserve(available);
530 qint64 readBytes = readFromStdout(ptr, available);
531 if (readBytes == -1) {
532 processError = QProcess::ReadError;
533 q->setErrorString(QProcess::tr("Error reading from process"));
534 emit q->error(processError);
535#if defined QPROCESS_DEBUG
536 qDebug("QProcessPrivate::canReadStandardOutput(), failed to read from the process");
537#endif
538 return false;
539 }
540#if defined QPROCESS_DEBUG
541 qDebug("QProcessPrivate::canReadStandardOutput(), read %d bytes from the process' output",
542 int(readBytes));
543#endif
544
545 if (stdoutChannel.closed) {
546 outputReadBuffer.chop(readBytes);
547 return false;
548 }
549
550 outputReadBuffer.chop(available - readBytes);
551
552 bool didRead = false;
553 if (readBytes == 0) {
554 if (stdoutChannel.notifier)
555 stdoutChannel.notifier->setEnabled(false);
556 } else if (processChannel == QProcess::StandardOutput) {
557 didRead = true;
558 if (!emittedReadyRead) {
559 emittedReadyRead = true;
560 emit q->readyRead();
561 emittedReadyRead = false;
562 }
563 }
564 emit q->readyReadStandardOutput();
565 return didRead;
566}
567
568/*! \internal
569*/
570bool QProcessPrivate::_q_canReadStandardError()
571{
572 Q_Q(QProcess);
573 qint64 available = bytesAvailableFromStderr();
574 if (available == 0) {
575 if (stderrChannel.notifier)
576 stderrChannel.notifier->setEnabled(false);
577 destroyPipe(stderrChannel.pipe);
578 return false;
579 }
580
581 char *ptr = errorReadBuffer.reserve(available);
582 qint64 readBytes = readFromStderr(ptr, available);
583 if (readBytes == -1) {
584 processError = QProcess::ReadError;
585 q->setErrorString(QProcess::tr("Error reading from process"));
586 emit q->error(processError);
587 return false;
588 }
589 if (stderrChannel.closed) {
590 errorReadBuffer.chop(readBytes);
591 return false;
592 }
593
594 errorReadBuffer.chop(available - readBytes);
595
596 bool didRead = false;
597 if (readBytes == 0) {
598 if (stderrChannel.notifier)
599 stderrChannel.notifier->setEnabled(false);
600 } else if (processChannel == QProcess::StandardError) {
601 didRead = true;
602 if (!emittedReadyRead) {
603 emittedReadyRead = true;
604 emit q->readyRead();
605 emittedReadyRead = false;
606 }
607 }
608 emit q->readyReadStandardError();
609 return didRead;
610}
611
612/*! \internal
613*/
614bool QProcessPrivate::_q_canWrite()
615{
616 Q_Q(QProcess);
617 if (stdinChannel.notifier)
618 stdinChannel.notifier->setEnabled(false);
619
620 if (writeBuffer.isEmpty()) {
621#if defined QPROCESS_DEBUG
622 qDebug("QProcessPrivate::canWrite(), not writing anything (empty write buffer).");
623#endif
624 return false;
625 }
626
627 qint64 written = writeToStdin(writeBuffer.readPointer(),
628 writeBuffer.nextDataBlockSize());
629 if (written < 0) {
630 destroyPipe(stdinChannel.pipe);
631 processError = QProcess::WriteError;
632 q->setErrorString(QProcess::tr("Error writing to process"));
633#if defined(QPROCESS_DEBUG) && !defined(Q_OS_WINCE)
634 qDebug("QProcessPrivate::canWrite(), failed to write (%s)", strerror(errno));
635#endif
636 emit q->error(processError);
637 return false;
638 }
639
640#if defined QPROCESS_DEBUG
641 qDebug("QProcessPrivate::canWrite(), wrote %d bytes to the process input", int(written));
642#endif
643
644 writeBuffer.free(written);
645 if (!emittedBytesWritten) {
646 emittedBytesWritten = true;
647 emit q->bytesWritten(written);
648 emittedBytesWritten = false;
649 }
650 if (stdinChannel.notifier && !writeBuffer.isEmpty())
651 stdinChannel.notifier->setEnabled(true);
652 if (writeBuffer.isEmpty() && stdinChannel.closed)
653 closeWriteChannel();
654 return true;
655}
656
657/*! \internal
658*/
659bool QProcessPrivate::_q_processDied()
660{
661 Q_Q(QProcess);
662#if defined QPROCESS_DEBUG
663 qDebug("QProcessPrivate::_q_processDied()");
664#endif
665#if defined(Q_OS_UNIX) || defined(Q_OS_OS2)
666 if (!waitForDeadChild())
667 return false;
668#endif
669#ifdef Q_OS_WIN
670 if (processFinishedNotifier)
671 processFinishedNotifier->setEnabled(false);
672#endif
673
674 // the process may have died before it got a chance to report that it was
675 // either running or stopped, so we will call _q_startupNotification() and
676 // give it a chance to emit started() or error(FailedToStart).
677 if (processState == QProcess::Starting) {
678 if (!_q_startupNotification())
679 return true;
680 }
681
682 if (dying) {
683 // at this point we know the process is dead. prevent
684 // reentering this slot recursively by calling waitForFinished()
685 // or opening a dialog inside slots connected to the readyRead
686 // signals emitted below.
687 return true;
688 }
689 dying = true;
690
691 // in case there is data in the pipe line and this slot by chance
692 // got called before the read notifications, call these two slots
693 // so the data is made available before the process dies.
694 _q_canReadStandardOutput();
695 _q_canReadStandardError();
696
697 findExitCode();
698
699 if (crashed) {
700 exitStatus = QProcess::CrashExit;
701 processError = QProcess::Crashed;
702 q->setErrorString(QProcess::tr("Process crashed"));
703 emit q->error(processError);
704 }
705
706 bool wasRunning = (processState == QProcess::Running);
707
708 cleanup();
709
710 if (wasRunning) {
711 // we received EOF now:
712 emit q->readChannelFinished();
713 // in the future:
714 //emit q->standardOutputClosed();
715 //emit q->standardErrorClosed();
716
717 emit q->finished(exitCode);
718 emit q->finished(exitCode, exitStatus);
719 }
720#if defined QPROCESS_DEBUG
721 qDebug("QProcessPrivate::_q_processDied() process is dead");
722#endif
723 return true;
724}
725
726/*! \internal
727*/
728bool QProcessPrivate::_q_startupNotification()
729{
730 Q_Q(QProcess);
731#if defined QPROCESS_DEBUG
732 qDebug("QProcessPrivate::startupNotification()");
733#endif
734
735 if (startupSocketNotifier)
736 startupSocketNotifier->setEnabled(false);
737 if (processStarted()) {
738 q->setProcessState(QProcess::Running);
739 emit q->started();
740 return true;
741 }
742
743 q->setProcessState(QProcess::NotRunning);
744 processError = QProcess::FailedToStart;
745 emit q->error(processError);
746#ifdef Q_OS_UNIX
747 // make sure the process manager removes this entry
748 waitForDeadChild();
749 findExitCode();
750#endif
751 cleanup();
752 return false;
753}
754
755/*! \internal
756*/
757void QProcessPrivate::closeWriteChannel()
758{
759#if defined QPROCESS_DEBUG
760 qDebug("QProcessPrivate::closeWriteChannel()");
761#endif
762 if (stdinChannel.notifier) {
763 extern void qDeleteInEventHandler(QObject *o);
764 stdinChannel.notifier->setEnabled(false);
765 if (stdinChannel.notifier) {
766 qDeleteInEventHandler(stdinChannel.notifier);
767 stdinChannel.notifier = 0;
768 }
769 }
770#ifdef Q_OS_WIN
771 // ### Find a better fix, feeding the process little by little
772 // instead.
773 flushPipeWriter();
774#endif
775 destroyPipe(stdinChannel.pipe);
776}
777
778/*!
779 Constructs a QProcess object with the given \a parent.
780*/
781QProcess::QProcess(QObject *parent)
782 : QIODevice(*new QProcessPrivate, parent)
783{
784#if defined QPROCESS_DEBUG
785 qDebug("QProcess::QProcess(%p)", parent);
786#endif
787}
788
789/*!
790 Destructs the QProcess object, i.e., killing the process.
791
792 Note that this function will not return until the process is
793 terminated.
794*/
795QProcess::~QProcess()
796{
797 Q_D(QProcess);
798 if (d->processState != NotRunning) {
799 qWarning("QProcess: Destroyed while process is still running.");
800 kill();
801 waitForFinished();
802 }
803#ifdef Q_OS_UNIX
804 // make sure the process manager removes this entry
805 d->findExitCode();
806#endif
807 d->cleanup();
808}
809
810/*!
811 \obsolete
812 Returns the read channel mode of the QProcess. This function is
813 equivalent to processChannelMode()
814
815 \sa processChannelMode()
816*/
817QProcess::ProcessChannelMode QProcess::readChannelMode() const
818{
819 return processChannelMode();
820}
821
822/*!
823 \obsolete
824
825 Use setProcessChannelMode(\a mode) instead.
826
827 \sa setProcessChannelMode()
828*/
829void QProcess::setReadChannelMode(ProcessChannelMode mode)
830{
831 setProcessChannelMode(mode);
832}
833
834/*!
835 \since 4.2
836
837 Returns the channel mode of the QProcess standard output and
838 standard error channels.
839
840 \sa setReadChannelMode(), ProcessChannelMode, setReadChannel()
841*/
842QProcess::ProcessChannelMode QProcess::processChannelMode() const
843{
844 Q_D(const QProcess);
845 return d->processChannelMode;
846}
847
848/*!
849 \since 4.2
850
851 Sets the channel mode of the QProcess standard output and standard
852 error channels to the \a mode specified.
853 This mode will be used the next time start() is called. For example:
854
855 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 0
856
857 \sa readChannelMode(), ProcessChannelMode, setReadChannel()
858*/
859void QProcess::setProcessChannelMode(ProcessChannelMode mode)
860{
861 Q_D(QProcess);
862 d->processChannelMode = mode;
863}
864
865/*!
866 Returns the current read channel of the QProcess.
867
868 \sa setReadChannel()
869*/
870QProcess::ProcessChannel QProcess::readChannel() const
871{
872 Q_D(const QProcess);
873 return d->processChannel;
874}
875
876/*!
877 Sets the current read channel of the QProcess to the given \a
878 channel. The current input channel is used by the functions
879 read(), readAll(), readLine(), and getChar(). It also determines
880 which channel triggers QProcess to emit readyRead().
881
882 \sa readChannel()
883*/
884void QProcess::setReadChannel(ProcessChannel channel)
885{
886 Q_D(QProcess);
887 if (d->processChannel != channel) {
888 QByteArray buf = d->buffer.readAll();
889 if (d->processChannel == QProcess::StandardOutput) {
890 for (int i = buf.size() - 1; i >= 0; --i)
891 d->outputReadBuffer.ungetChar(buf.at(i));
892 } else {
893 for (int i = buf.size() - 1; i >= 0; --i)
894 d->errorReadBuffer.ungetChar(buf.at(i));
895 }
896 }
897 d->processChannel = channel;
898}
899
900/*!
901 Closes the read channel \a channel. After calling this function,
902 QProcess will no longer receive data on the channel. Any data that
903 has already been received is still available for reading.
904
905 Call this function to save memory, if you are not interested in
906 the output of the process.
907
908 \sa closeWriteChannel(), setReadChannel()
909*/
910void QProcess::closeReadChannel(ProcessChannel channel)
911{
912 Q_D(QProcess);
913
914 if (channel == StandardOutput)
915 d->stdoutChannel.closed = true;
916 else
917 d->stderrChannel.closed = true;
918}
919
920/*!
921 Schedules the write channel of QProcess to be closed. The channel
922 will close once all data has been written to the process. After
923 calling this function, any attempts to write to the process will
924 fail.
925
926 Closing the write channel is necessary for programs that read
927 input data until the channel has been closed. For example, the
928 program "more" is used to display text data in a console on both
929 Unix and Windows. But it will not display the text data until
930 QProcess's write channel has been closed. Example:
931
932 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 1
933
934 The write channel is implicitly opened when start() is called.
935
936 \sa closeReadChannel()
937*/
938void QProcess::closeWriteChannel()
939{
940 Q_D(QProcess);
941 d->stdinChannel.closed = true; // closing
942 if (d->writeBuffer.isEmpty())
943 d->closeWriteChannel();
944}
945
946/*!
947 \since 4.2
948
949 Redirects the process' standard input to the file indicated by \a
950 fileName. When an input redirection is in place, the QProcess
951 object will be in read-only mode (calling write() will result in
952 error).
953
954 If the file \a fileName does not exist at the moment start() is
955 called or is not readable, starting the process will fail.
956
957 Calling setStandardInputFile() after the process has started has no
958 effect.
959
960 \sa setStandardOutputFile(), setStandardErrorFile(),
961 setStandardOutputProcess()
962*/
963void QProcess::setStandardInputFile(const QString &fileName)
964{
965 Q_D(QProcess);
966 d->stdinChannel = fileName;
967}
968
969/*!
970 \since 4.2
971
972 Redirects the process' standard output to the file \a
973 fileName. When the redirection is in place, the standard output
974 read channel is closed: reading from it using read() will always
975 fail, as will readAllStandardOutput().
976
977 If the file \a fileName doesn't exist at the moment start() is
978 called, it will be created. If it cannot be created, the starting
979 will fail.
980
981 If the file exists and \a mode is QIODevice::Truncate, the file
982 will be truncated. Otherwise (if \a mode is QIODevice::Append),
983 the file will be appended to.
984
985 Calling setStandardOutputFile() after the process has started has
986 no effect.
987
988 \sa setStandardInputFile(), setStandardErrorFile(),
989 setStandardOutputProcess()
990*/
991void QProcess::setStandardOutputFile(const QString &fileName, OpenMode mode)
992{
993 Q_ASSERT(mode == Append || mode == Truncate);
994 Q_D(QProcess);
995
996 d->stdoutChannel = fileName;
997 d->stdoutChannel.append = mode == Append;
998}
999
1000/*!
1001 \since 4.2
1002
1003 Redirects the process' standard error to the file \a
1004 fileName. When the redirection is in place, the standard error
1005 read channel is closed: reading from it using read() will always
1006 fail, as will readAllStandardError(). The file will be appended to
1007 if \a mode is Append, otherwise, it will be truncated.
1008
1009 See setStandardOutputFile() for more information on how the file
1010 is opened.
1011
1012 Note: if setProcessChannelMode() was called with an argument of
1013 QProcess::MergedChannels, this function has no effect.
1014
1015 \sa setStandardInputFile(), setStandardOutputFile(),
1016 setStandardOutputProcess()
1017*/
1018void QProcess::setStandardErrorFile(const QString &fileName, OpenMode mode)
1019{
1020 Q_ASSERT(mode == Append || mode == Truncate);
1021 Q_D(QProcess);
1022
1023 d->stderrChannel = fileName;
1024 d->stderrChannel.append = mode == Append;
1025}
1026
1027/*!
1028 \since 4.2
1029
1030 Pipes the standard output stream of this process to the \a
1031 destination process' standard input.
1032
1033 The following shell command:
1034 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 2
1035
1036 Can be accomplished with QProcesses with the following code:
1037 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 3
1038*/
1039void QProcess::setStandardOutputProcess(QProcess *destination)
1040{
1041 QProcessPrivate *dfrom = d_func();
1042 QProcessPrivate *dto = destination->d_func();
1043 dfrom->stdoutChannel.pipeTo(dto);
1044 dto->stdinChannel.pipeFrom(dfrom);
1045}
1046
1047/*!
1048 If QProcess has been assigned a working directory, this function returns
1049 the working directory that the QProcess will enter before the program has
1050 started. Otherwise, (i.e., no directory has been assigned,) an empty
1051 string is returned, and QProcess will use the application's current
1052 working directory instead.
1053
1054 \sa setWorkingDirectory()
1055*/
1056QString QProcess::workingDirectory() const
1057{
1058 Q_D(const QProcess);
1059 return d->workingDirectory;
1060}
1061
1062/*!
1063 Sets the working directory to \a dir. QProcess will start the
1064 process in this directory. The default behavior is to start the
1065 process in the working directory of the calling process.
1066
1067 \sa workingDirectory(), start()
1068*/
1069void QProcess::setWorkingDirectory(const QString &dir)
1070{
1071 Q_D(QProcess);
1072 d->workingDirectory = dir;
1073}
1074
1075/*!
1076 Returns the native process identifier for the running process, if
1077 available. If no process is currently running, 0 is returned.
1078*/
1079Q_PID QProcess::pid() const
1080{
1081 Q_D(const QProcess);
1082 return d->pid;
1083}
1084
1085/*! \reimp
1086
1087 This function operates on the current read channel.
1088
1089 \sa readChannel(), setReadChannel()
1090*/
1091bool QProcess::canReadLine() const
1092{
1093 Q_D(const QProcess);
1094 const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1095 ? &d->errorReadBuffer
1096 : &d->outputReadBuffer;
1097 return readBuffer->canReadLine() || QIODevice::canReadLine();
1098}
1099
1100/*!
1101 Closes all communication with the process and kills it. After calling this
1102 function, QProcess will no longer emit readyRead(), and data can no
1103 longer be read or written.
1104*/
1105void QProcess::close()
1106{
1107 emit aboutToClose();
1108 while (waitForBytesWritten(-1))
1109 ;
1110 kill();
1111 waitForFinished(-1);
1112 QIODevice::close();
1113}
1114
1115/*! \reimp
1116
1117 Returns true if the process is not running, and no more data is available
1118 for reading; otherwise returns false.
1119*/
1120bool QProcess::atEnd() const
1121{
1122 Q_D(const QProcess);
1123 const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1124 ? &d->errorReadBuffer
1125 : &d->outputReadBuffer;
1126 return QIODevice::atEnd() && (!isOpen() || readBuffer->isEmpty());
1127}
1128
1129/*! \reimp
1130*/
1131bool QProcess::isSequential() const
1132{
1133 return true;
1134}
1135
1136/*! \reimp
1137*/
1138qint64 QProcess::bytesAvailable() const
1139{
1140 Q_D(const QProcess);
1141 const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1142 ? &d->errorReadBuffer
1143 : &d->outputReadBuffer;
1144#if defined QPROCESS_DEBUG
1145 qDebug("QProcess::bytesAvailable() == %i (%s)", readBuffer->size(),
1146 (d->processChannel == QProcess::StandardError) ? "stderr" : "stdout");
1147#endif
1148 return readBuffer->size() + QIODevice::bytesAvailable();
1149}
1150
1151/*! \reimp
1152*/
1153qint64 QProcess::bytesToWrite() const
1154{
1155 Q_D(const QProcess);
1156 qint64 size = d->writeBuffer.size();
1157#ifdef Q_OS_WIN
1158 size += d->pipeWriterBytesToWrite();
1159#endif
1160 return size;
1161}
1162
1163/*!
1164 Returns the type of error that occurred last.
1165
1166 \sa state()
1167*/
1168QProcess::ProcessError QProcess::error() const
1169{
1170 Q_D(const QProcess);
1171 return d->processError;
1172}
1173
1174/*!
1175 Returns the current state of the process.
1176
1177 \sa stateChanged(), error()
1178*/
1179QProcess::ProcessState QProcess::state() const
1180{
1181 Q_D(const QProcess);
1182 return d->processState;
1183}
1184
1185/*!
1186 Sets the environment that QProcess will use when starting a process to the
1187 \a environment specified which consists of a list of key=value pairs.
1188
1189 For example, the following code adds the \c{C:\\BIN} directory to the list of
1190 executable paths (\c{PATHS}) on Windows:
1191
1192 \snippet doc/src/snippets/qprocess-environment/main.cpp 0
1193
1194 \sa environment(), systemEnvironment()
1195*/
1196void QProcess::setEnvironment(const QStringList &environment)
1197{
1198 Q_D(QProcess);
1199 d->environment = environment;
1200}
1201
1202/*!
1203 Returns the environment that QProcess will use when starting a
1204 process, or an empty QStringList if no environment has been set
1205 using setEnvironment(). If no environment has been set, the
1206 environment of the calling process will be used.
1207
1208 \note The environment settings are ignored on Windows CE,
1209 as there is no concept of an environment.
1210
1211 \sa setEnvironment(), systemEnvironment()
1212*/
1213QStringList QProcess::environment() const
1214{
1215 Q_D(const QProcess);
1216 return d->environment;
1217}
1218
1219/*!
1220 Blocks until the process has started and the started() signal has
1221 been emitted, or until \a msecs milliseconds have passed.
1222
1223 Returns true if the process was started successfully; otherwise
1224 returns false (if the operation timed out or if an error
1225 occurred).
1226
1227 This function can operate without an event loop. It is
1228 useful when writing non-GUI applications and when performing
1229 I/O operations in a non-GUI thread.
1230
1231 \warning Calling this function from the main (GUI) thread
1232 might cause your user interface to freeze.
1233
1234 If msecs is -1, this function will not time out.
1235
1236 \sa started(), waitForReadyRead(), waitForBytesWritten(), waitForFinished()
1237*/
1238bool QProcess::waitForStarted(int msecs)
1239{
1240 Q_D(QProcess);
1241 if (d->processState == QProcess::Starting) {
1242 if (!d->waitForStarted(msecs))
1243 return false;
1244 setProcessState(QProcess::Running);
1245 emit started();
1246 }
1247 return d->processState == QProcess::Running;
1248}
1249
1250/*! \reimp
1251*/
1252bool QProcess::waitForReadyRead(int msecs)
1253{
1254 Q_D(QProcess);
1255
1256 if (d->processState == QProcess::NotRunning)
1257 return false;
1258 if (d->processChannel == QProcess::StandardOutput && d->stdoutChannel.closed)
1259 return false;
1260 if (d->processChannel == QProcess::StandardError && d->stderrChannel.closed)
1261 return false;
1262 return d->waitForReadyRead(msecs);
1263}
1264
1265/*! \reimp
1266*/
1267bool QProcess::waitForBytesWritten(int msecs)
1268{
1269 Q_D(QProcess);
1270 if (d->processState == QProcess::NotRunning)
1271 return false;
1272 if (d->processState == QProcess::Starting) {
1273 QTime stopWatch;
1274 stopWatch.start();
1275 bool started = waitForStarted(msecs);
1276 if (!started)
1277 return false;
1278 if (msecs != -1)
1279 msecs -= stopWatch.elapsed();
1280 }
1281
1282 return d->waitForBytesWritten(msecs);
1283}
1284
1285/*!
1286 Blocks until the process has finished and the finished() signal
1287 has been emitted, or until \a msecs milliseconds have passed.
1288
1289 Returns true if the process finished; otherwise returns false (if
1290 the operation timed out or if an error occurred).
1291
1292 This function can operate without an event loop. It is
1293 useful when writing non-GUI applications and when performing
1294 I/O operations in a non-GUI thread.
1295
1296 \warning Calling this function from the main (GUI) thread
1297 might cause your user interface to freeze.
1298
1299 If msecs is -1, this function will not time out.
1300
1301 \sa finished(), waitForStarted(), waitForReadyRead(), waitForBytesWritten()
1302*/
1303bool QProcess::waitForFinished(int msecs)
1304{
1305 Q_D(QProcess);
1306 if (d->processState == QProcess::NotRunning)
1307 return false;
1308 if (d->processState == QProcess::Starting) {
1309 QTime stopWatch;
1310 stopWatch.start();
1311 bool started = waitForStarted(msecs);
1312 if (!started)
1313 return false;
1314 if (msecs != -1)
1315 msecs -= stopWatch.elapsed();
1316 }
1317
1318 return d->waitForFinished(msecs);
1319}
1320
1321/*!
1322 Sets the current state of the QProcess to the \a state specified.
1323
1324 \sa state()
1325*/
1326void QProcess::setProcessState(ProcessState state)
1327{
1328 Q_D(QProcess);
1329 if (d->processState == state)
1330 return;
1331 d->processState = state;
1332 emit stateChanged(state);
1333}
1334
1335/*!
1336 This function is called in the child process context just before the
1337 program is executed on Unix or Mac OS X (i.e., after \e fork(), but before
1338 \e execve()). Reimplement this function to do last minute initialization
1339 of the child process. Example:
1340
1341 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 4
1342
1343 You cannot exit the process (by calling exit(), for instance) from
1344 this function. If you need to stop the program before it starts
1345 execution, your workaround is to emit finished() and then call
1346 exit().
1347
1348 \warning This function is called by QProcess on Unix and Mac OS X
1349 only. On Windows, it is not called.
1350*/
1351void QProcess::setupChildProcess()
1352{
1353}
1354
1355/*! \reimp
1356*/
1357qint64 QProcess::readData(char *data, qint64 maxlen)
1358{
1359 Q_D(QProcess);
1360 QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1361 ? &d->errorReadBuffer
1362 : &d->outputReadBuffer;
1363
1364 if (maxlen == 1 && !readBuffer->isEmpty()) {
1365 int c = readBuffer->getChar();
1366 if (c == -1) {
1367#if defined QPROCESS_DEBUG
1368 qDebug("QProcess::readData(%p \"%s\", %d) == -1",
1369 data, qt_prettyDebug(data, 1, maxlen).constData(), 1);
1370#endif
1371 return -1;
1372 }
1373 *data = (char) c;
1374#if defined QPROCESS_DEBUG
1375 qDebug("QProcess::readData(%p \"%s\", %d) == 1",
1376 data, qt_prettyDebug(data, 1, maxlen).constData(), 1);
1377#endif
1378 return 1;
1379 }
1380
1381 qint64 bytesToRead = qint64(qMin(readBuffer->size(), (int)maxlen));
1382 qint64 readSoFar = 0;
1383 while (readSoFar < bytesToRead) {
1384 const char *ptr = readBuffer->readPointer();
1385 int bytesToReadFromThisBlock = qMin<qint64>(bytesToRead - readSoFar,
1386 readBuffer->nextDataBlockSize());
1387 memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
1388 readSoFar += bytesToReadFromThisBlock;
1389 readBuffer->free(bytesToReadFromThisBlock);
1390 }
1391
1392#if defined QPROCESS_DEBUG
1393 qDebug("QProcess::readData(%p \"%s\", %lld) == %lld",
1394 data, qt_prettyDebug(data, readSoFar, 16).constData(), maxlen, readSoFar);
1395#endif
1396 if (!readSoFar && d->processState == QProcess::NotRunning)
1397 return -1; // EOF
1398 return readSoFar;
1399}
1400
1401/*! \reimp
1402*/
1403qint64 QProcess::writeData(const char *data, qint64 len)
1404{
1405 Q_D(QProcess);
1406
1407#if defined(Q_OS_WINCE)
1408 Q_UNUSED(data);
1409 Q_UNUSED(len);
1410 d->processError = QProcess::WriteError;
1411 setErrorString(tr("Error writing to process"));
1412 emit error(d->processError);
1413 return -1;
1414#endif
1415
1416 if (d->stdinChannel.closed) {
1417#if defined QPROCESS_DEBUG
1418 qDebug("QProcess::writeData(%p \"%s\", %lld) == 0 (write channel closing)",
1419 data, qt_prettyDebug(data, len, 16).constData(), len);
1420#endif
1421 return 0;
1422 }
1423
1424 if (len == 1) {
1425 d->writeBuffer.putChar(*data);
1426 if (d->stdinChannel.notifier)
1427 d->stdinChannel.notifier->setEnabled(true);
1428#if defined QPROCESS_DEBUG
1429 qDebug("QProcess::writeData(%p \"%s\", %lld) == 1 (written to buffer)",
1430 data, qt_prettyDebug(data, len, 16).constData(), len);
1431#endif
1432 return 1;
1433 }
1434
1435 char *dest = d->writeBuffer.reserve(len);
1436 memcpy(dest, data, len);
1437 if (d->stdinChannel.notifier)
1438 d->stdinChannel.notifier->setEnabled(true);
1439#if defined QPROCESS_DEBUG
1440 qDebug("QProcess::writeData(%p \"%s\", %lld) == %lld (written to buffer)",
1441 data, qt_prettyDebug(data, len, 16).constData(), len, len);
1442#endif
1443 return len;
1444}
1445
1446/*!
1447 Regardless of the current read channel, this function returns all
1448 data available from the standard output of the process as a
1449 QByteArray.
1450
1451 \sa readyReadStandardOutput(), readAllStandardError(), readChannel(), setReadChannel()
1452*/
1453QByteArray QProcess::readAllStandardOutput()
1454{
1455 ProcessChannel tmp = readChannel();
1456 setReadChannel(StandardOutput);
1457 QByteArray data = readAll();
1458 setReadChannel(tmp);
1459 return data;
1460}
1461
1462/*!
1463 Regardless of the current read channel, this function returns all
1464 data available from the standard error of the process as a
1465 QByteArray.
1466
1467 \sa readyReadStandardError(), readAllStandardOutput(), readChannel(), setReadChannel()
1468*/
1469QByteArray QProcess::readAllStandardError()
1470{
1471 ProcessChannel tmp = readChannel();
1472 setReadChannel(StandardError);
1473 QByteArray data = readAll();
1474 setReadChannel(tmp);
1475 return data;
1476}
1477
1478/*!
1479 Starts the program \a program in a new process, if one is not already
1480 running, passing the command line arguments in \a arguments. The OpenMode
1481 is set to \a mode.
1482
1483 The QProcess object will immediately enter the Starting state. If the
1484 process starts successfully, QProcess will emit started(); otherwise,
1485 error() will be emitted. If the QProcess object is already running a
1486 process, a warning may be printed at the console, and the existing
1487 process will continue running.
1488
1489 Note that arguments that contain spaces are not passed to the
1490 process as separate arguments.
1491
1492 \bold{Windows:} Arguments that contain spaces are wrapped in quotes.
1493
1494 \note Processes are started asynchronously, which means the started()
1495 and error() signals may be delayed. Call waitForStarted() to make
1496 sure the process has started (or has failed to start) and those signals
1497 have been emitted.
1498
1499 \sa pid(), started(), waitForStarted()
1500*/
1501void QProcess::start(const QString &program, const QStringList &arguments, OpenMode mode)
1502{
1503 Q_D(QProcess);
1504 if (d->processState != NotRunning) {
1505 qWarning("QProcess::start: Process is already running");
1506 return;
1507 }
1508
1509#if defined QPROCESS_DEBUG
1510 qDebug() << "QProcess::start(" << program << "," << arguments << "," << mode << ")";
1511#endif
1512
1513 d->outputReadBuffer.clear();
1514 d->errorReadBuffer.clear();
1515
1516 if (d->stdinChannel.type != QProcessPrivate::Channel::Normal)
1517 mode &= ~WriteOnly; // not open for writing
1518 if (d->stdoutChannel.type != QProcessPrivate::Channel::Normal &&
1519 (d->stderrChannel.type != QProcessPrivate::Channel::Normal ||
1520 d->processChannelMode == MergedChannels))
1521 mode &= ~ReadOnly; // not open for reading
1522 if (mode == 0)
1523 mode = Unbuffered;
1524 QIODevice::open(mode);
1525
1526 d->stdinChannel.closed = false;
1527 d->stdoutChannel.closed = false;
1528 d->stderrChannel.closed = false;
1529
1530 d->program = program;
1531 d->arguments = arguments;
1532
1533 d->exitCode = 0;
1534 d->exitStatus = NormalExit;
1535 d->processError = QProcess::UnknownError;
1536 d->errorString.clear();
1537 d->startProcess();
1538}
1539
1540
1541static QStringList parseCombinedArgString(const QString &program)
1542{
1543 QStringList args;
1544 QString tmp;
1545 int quoteCount = 0;
1546 bool inQuote = false;
1547
1548 // handle quoting. tokens can be surrounded by double quotes
1549 // "hello world". three consecutive double quotes represent
1550 // the quote character itself.
1551 for (int i = 0; i < program.size(); ++i) {
1552 if (program.at(i) == QLatin1Char('"')) {
1553 ++quoteCount;
1554 if (quoteCount == 3) {
1555 // third consecutive quote
1556 quoteCount = 0;
1557 tmp += program.at(i);
1558 }
1559 continue;
1560 }
1561 if (quoteCount) {
1562 if (quoteCount == 1)
1563 inQuote = !inQuote;
1564 quoteCount = 0;
1565 }
1566 if (!inQuote && program.at(i).isSpace()) {
1567 if (!tmp.isEmpty()) {
1568 args += tmp;
1569 tmp.clear();
1570 }
1571 } else {
1572 tmp += program.at(i);
1573 }
1574 }
1575 if (!tmp.isEmpty())
1576 args += tmp;
1577
1578 return args;
1579}
1580
1581/*!
1582 \overload
1583
1584 Starts the program \a program in a new process, if one is not already
1585 running. \a program is a single string of text containing both the
1586 program name and its arguments. The arguments are separated by one or
1587 more spaces. For example:
1588
1589 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 5
1590
1591 The \a program string can also contain quotes, to ensure that arguments
1592 containing spaces are correctly supplied to the new process. For example:
1593
1594 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 6
1595
1596 If the QProcess object is already running a process, a warning may be
1597 printed at the console, and the existing process will continue running.
1598
1599 Note that, on Windows, quotes need to be both escaped and quoted.
1600 For example, the above code would be specified in the following
1601 way to ensure that \c{"My Documents"} is used as the argument to
1602 the \c dir executable:
1603
1604 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 7
1605
1606 The OpenMode is set to \a mode.
1607*/
1608void QProcess::start(const QString &program, OpenMode mode)
1609{
1610 QStringList args = parseCombinedArgString(program);
1611 if (args.isEmpty()) {
1612 Q_D(QProcess);
1613 d->processError = QProcess::FailedToStart;
1614 setErrorString(tr("No program defined"));
1615 emit error(d->processError);
1616 return;
1617 }
1618
1619 QString prog = args.first();
1620 args.removeFirst();
1621
1622 start(prog, args, mode);
1623}
1624
1625/*!
1626 Attempts to terminate the process.
1627
1628 The process may not exit as a result of calling this function (it is given
1629 the chance to prompt the user for any unsaved files, etc).
1630
1631 On Windows, terminate() posts a WM_CLOSE message to all toplevel windows
1632 of the process and then to the main thread of the process itself. On Unix
1633 and Mac OS X the SIGTERM signal is sent.
1634
1635 Console applications on Windows that do not run an event loop, or whose
1636 event loop does not handle the WM_CLOSE message, can only be terminated by
1637 calling kill().
1638
1639 \sa kill()
1640*/
1641void QProcess::terminate()
1642{
1643 Q_D(QProcess);
1644 d->terminateProcess();
1645}
1646
1647/*!
1648 Kills the current process, causing it to exit immediately.
1649
1650 On Windows, kill() uses TerminateProcess, and on Unix and Mac OS X, the
1651 SIGKILL signal is sent to the process.
1652
1653 \sa terminate()
1654*/
1655void QProcess::kill()
1656{
1657 Q_D(QProcess);
1658 d->killProcess();
1659}
1660
1661/*!
1662 Returns the exit code of the last process that finished.
1663*/
1664int QProcess::exitCode() const
1665{
1666 Q_D(const QProcess);
1667 return d->exitCode;
1668}
1669
1670/*!
1671 \since 4.1
1672
1673 Returns the exit status of the last process that finished.
1674
1675 On Windows, if the process was terminated with TerminateProcess()
1676 from another application this function will still return NormalExit
1677 unless the exit code is less than 0.
1678*/
1679QProcess::ExitStatus QProcess::exitStatus() const
1680{
1681 Q_D(const QProcess);
1682 return d->exitStatus;
1683}
1684
1685/*!
1686 Starts the program \a program with the arguments \a arguments in a
1687 new process, waits for it to finish, and then returns the exit
1688 code of the process. Any data the new process writes to the
1689 console is forwarded to the calling process.
1690
1691 The environment and working directory are inherited by the calling
1692 process.
1693
1694 On Windows, arguments that contain spaces are wrapped in quotes.
1695*/
1696int QProcess::execute(const QString &program, const QStringList &arguments)
1697{
1698 QProcess process;
1699 process.setReadChannelMode(ForwardedChannels);
1700 process.start(program, arguments);
1701 process.waitForFinished(-1);
1702 return process.exitCode();
1703}
1704
1705/*!
1706 \overload
1707
1708 Starts the program \a program in a new process. \a program is a
1709 single string of text containing both the program name and its
1710 arguments. The arguments are separated by one or more spaces.
1711*/
1712int QProcess::execute(const QString &program)
1713{
1714 QProcess process;
1715 process.setReadChannelMode(ForwardedChannels);
1716 process.start(program);
1717 process.waitForFinished(-1);
1718 return process.exitCode();
1719}
1720
1721/*!
1722 Starts the program \a program with the arguments \a arguments in a
1723 new process, and detaches from it. Returns true on success;
1724 otherwise returns false. If the calling process exits, the
1725 detached process will continue to live.
1726
1727 Note that arguments that contain spaces are not passed to the
1728 process as separate arguments.
1729
1730 \bold{Unix:} The started process will run in its own session and act
1731 like a daemon.
1732
1733 \bold{Windows:} Arguments that contain spaces are wrapped in quotes.
1734 The started process will run as a regular standalone process.
1735
1736 The process will be started in the directory \a workingDirectory.
1737
1738 If the function is successful then *\a pid is set to the process
1739 identifier of the started process.
1740*/
1741bool QProcess::startDetached(const QString &program,
1742 const QStringList &arguments,
1743 const QString &workingDirectory,
1744 qint64 *pid)
1745{
1746 return QProcessPrivate::startDetached(program,
1747 arguments,
1748 workingDirectory,
1749 pid);
1750}
1751
1752/*!
1753 Starts the program \a program with the given \a arguments in a
1754 new process, and detaches from it. Returns true on success;
1755 otherwise returns false. If the calling process exits, the
1756 detached process will continue to live.
1757
1758 Note that arguments that contain spaces are not passed to the
1759 process as separate arguments.
1760
1761 \bold{Unix:} The started process will run in its own session and act
1762 like a daemon.
1763
1764 \bold{Windows:} Arguments that contain spaces are wrapped in quotes.
1765 The started process will run as a regular standalone process.
1766*/
1767bool QProcess::startDetached(const QString &program,
1768 const QStringList &arguments)
1769{
1770 return QProcessPrivate::startDetached(program, arguments);
1771}
1772
1773/*!
1774 \overload
1775
1776 Starts the program \a program in a new process. \a program is a
1777 single string of text containing both the program name and its
1778 arguments. The arguments are separated by one or more spaces.
1779
1780 The \a program string can also contain quotes, to ensure that arguments
1781 containing spaces are correctly supplied to the new process.
1782*/
1783bool QProcess::startDetached(const QString &program)
1784{
1785 QStringList args = parseCombinedArgString(program);
1786 if (args.isEmpty())
1787 return false;
1788
1789 QString prog = args.first();
1790 args.removeFirst();
1791
1792 return QProcessPrivate::startDetached(prog, args);
1793}
1794
1795QT_BEGIN_INCLUDE_NAMESPACE
1796#ifdef Q_OS_MAC
1797# include <crt_externs.h>
1798# define environ (*_NSGetEnviron())
1799#elif defined(Q_OS_WINCE)
1800 static char *qt_wince_environ[] = { 0 };
1801#define environ qt_wince_environ
1802#elif !defined(Q_OS_WIN)
1803 extern char **environ;
1804#endif
1805QT_END_INCLUDE_NAMESPACE
1806
1807/*!
1808 \since 4.1
1809
1810 Returns the environment of the calling process as a list of
1811 key=value pairs. Example:
1812
1813 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 8
1814
1815 \sa environment(), setEnvironment()
1816*/
1817QStringList QProcess::systemEnvironment()
1818{
1819 QStringList tmp;
1820 char *entry = 0;
1821 int count = 0;
1822 while ((entry = environ[count++]))
1823 tmp << QString::fromLocal8Bit(entry);
1824 return tmp;
1825}
1826
1827/*!
1828 \typedef Q_PID
1829 \relates QProcess
1830
1831 Typedef for the identifiers used to represent processes on the underlying
1832 platform. On Unix, this corresponds to \l qint64; on Windows, it
1833 corresponds to \c{_PROCESS_INFORMATION*}.
1834
1835 \sa QProcess::pid()
1836*/
1837
1838QT_END_NAMESPACE
1839
1840#include "moc_qprocess.cpp"
1841
1842#endif // QT_NO_PROCESS
1843
Note: See TracBrowser for help on using the repository browser.