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

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

corelib: QProcess: Implemented QProcess->QProcess redirection.

File size: 53.7 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#ifndef Q_OS_OS2
424 childStartedPipe[0] = INVALID_Q_PIPE;
425 childStartedPipe[1] = INVALID_Q_PIPE;
426 deathPipe[0] = INVALID_Q_PIPE;
427 deathPipe[1] = INVALID_Q_PIPE;
428#endif
429 exitCode = 0;
430 crashed = false;
431 dying = false;
432 emittedReadyRead = false;
433 emittedBytesWritten = false;
434#ifdef Q_WS_WIN
435 pipeWriter = 0;
436 processFinishedNotifier = 0;
437#endif // Q_WS_WIN
438#ifdef Q_OS_UNIX
439 serial = 0;
440#endif
441#ifdef Q_OS_OS2
442 init();
443#endif
444}
445
446/*! \internal
447*/
448QProcessPrivate::~QProcessPrivate()
449{
450#ifdef Q_OS_OS2
451 uninit();
452#endif
453 if (stdinChannel.process)
454 stdinChannel.process->stdoutChannel.clear();
455 if (stdoutChannel.process)
456 stdoutChannel.process->stdinChannel.clear();
457}
458
459/*! \internal
460*/
461void QProcessPrivate::cleanup()
462{
463 q_func()->setProcessState(QProcess::NotRunning);
464#ifdef Q_OS_WIN
465 if (pid) {
466 CloseHandle(pid->hThread);
467 CloseHandle(pid->hProcess);
468 delete pid;
469 pid = 0;
470 }
471 if (processFinishedNotifier) {
472 processFinishedNotifier->setEnabled(false);
473 qDeleteInEventHandler(processFinishedNotifier);
474 processFinishedNotifier = 0;
475 }
476
477#endif
478 pid = 0;
479 sequenceNumber = 0;
480 dying = false;
481
482 if (stdoutChannel.notifier) {
483 stdoutChannel.notifier->setEnabled(false);
484 qDeleteInEventHandler(stdoutChannel.notifier);
485 stdoutChannel.notifier = 0;
486 }
487 if (stderrChannel.notifier) {
488 stderrChannel.notifier->setEnabled(false);
489 qDeleteInEventHandler(stderrChannel.notifier);
490 stderrChannel.notifier = 0;
491 }
492 if (stdinChannel.notifier) {
493 stdinChannel.notifier->setEnabled(false);
494 qDeleteInEventHandler(stdinChannel.notifier);
495 stdinChannel.notifier = 0;
496 }
497 if (startupSocketNotifier) {
498 startupSocketNotifier->setEnabled(false);
499 qDeleteInEventHandler(startupSocketNotifier);
500 startupSocketNotifier = 0;
501 }
502 if (deathNotifier) {
503 deathNotifier->setEnabled(false);
504 qDeleteInEventHandler(deathNotifier);
505 deathNotifier = 0;
506 }
507 if (notifier) {
508 qDeleteInEventHandler(notifier);
509 notifier = 0;
510 }
511 destroyPipe(stdoutChannel.pipe);
512 destroyPipe(stderrChannel.pipe);
513 destroyPipe(stdinChannel.pipe);
514#ifndef Q_OS_OS2
515 destroyPipe(childStartedPipe);
516 destroyPipe(deathPipe);
517#else
518 pipeData[InPipe].bytesLeft = 0;
519 pipeData[OutPipe].bytesLeft = pipeData[ErrPipe].bytesLeft = 0;
520 pipeData[InPipe].newBytes = 0;
521 pipeData[OutPipe].newBytes = pipeData[ErrPipe].newBytes = 0;
522#endif
523#ifdef Q_OS_UNIX
524 serial = 0;
525#endif
526}
527
528/*! \internal
529*/
530bool QProcessPrivate::_q_canReadStandardOutput()
531{
532 Q_Q(QProcess);
533 qint64 available = bytesAvailableFromStdout();
534 if (available == 0) {
535 if (stdoutChannel.notifier)
536 stdoutChannel.notifier->setEnabled(false);
537 destroyPipe(stdoutChannel.pipe);
538#if defined QPROCESS_DEBUG
539 qDebug("QProcessPrivate::canReadStandardOutput(), 0 bytes available");
540#endif
541 return false;
542 }
543
544 char *ptr = outputReadBuffer.reserve(available);
545 qint64 readBytes = readFromStdout(ptr, available);
546 if (readBytes == -1) {
547 processError = QProcess::ReadError;
548 q->setErrorString(QProcess::tr("Error reading from process"));
549 emit q->error(processError);
550#if defined QPROCESS_DEBUG
551 qDebug("QProcessPrivate::canReadStandardOutput(), failed to read from the process");
552#endif
553 return false;
554 }
555#if defined QPROCESS_DEBUG
556 qDebug("QProcessPrivate::canReadStandardOutput(), read %d bytes from the process' output",
557 int(readBytes));
558#endif
559
560 if (stdoutChannel.closed) {
561 outputReadBuffer.chop(readBytes);
562 return false;
563 }
564
565 outputReadBuffer.chop(available - readBytes);
566
567 bool didRead = false;
568 if (readBytes == 0) {
569 if (stdoutChannel.notifier)
570 stdoutChannel.notifier->setEnabled(false);
571 } else if (processChannel == QProcess::StandardOutput) {
572 didRead = true;
573 if (!emittedReadyRead) {
574 emittedReadyRead = true;
575 emit q->readyRead();
576 emittedReadyRead = false;
577 }
578 }
579 emit q->readyReadStandardOutput();
580 return didRead;
581}
582
583/*! \internal
584*/
585bool QProcessPrivate::_q_canReadStandardError()
586{
587 Q_Q(QProcess);
588 qint64 available = bytesAvailableFromStderr();
589 if (available == 0) {
590 if (stderrChannel.notifier)
591 stderrChannel.notifier->setEnabled(false);
592 destroyPipe(stderrChannel.pipe);
593 return false;
594 }
595
596 char *ptr = errorReadBuffer.reserve(available);
597 qint64 readBytes = readFromStderr(ptr, available);
598 if (readBytes == -1) {
599 processError = QProcess::ReadError;
600 q->setErrorString(QProcess::tr("Error reading from process"));
601 emit q->error(processError);
602 return false;
603 }
604 if (stderrChannel.closed) {
605 errorReadBuffer.chop(readBytes);
606 return false;
607 }
608
609 errorReadBuffer.chop(available - readBytes);
610
611 bool didRead = false;
612 if (readBytes == 0) {
613 if (stderrChannel.notifier)
614 stderrChannel.notifier->setEnabled(false);
615 } else if (processChannel == QProcess::StandardError) {
616 didRead = true;
617 if (!emittedReadyRead) {
618 emittedReadyRead = true;
619 emit q->readyRead();
620 emittedReadyRead = false;
621 }
622 }
623 emit q->readyReadStandardError();
624 return didRead;
625}
626
627/*! \internal
628*/
629bool QProcessPrivate::_q_canWrite()
630{
631 Q_Q(QProcess);
632 if (stdinChannel.notifier)
633 stdinChannel.notifier->setEnabled(false);
634
635 if (writeBuffer.isEmpty()) {
636#if defined QPROCESS_DEBUG
637 qDebug("QProcessPrivate::canWrite(), not writing anything (empty write buffer).");
638#endif
639 return false;
640 }
641
642 qint64 written = writeToStdin(writeBuffer.readPointer(),
643 writeBuffer.nextDataBlockSize());
644 if (written < 0) {
645 destroyPipe(stdinChannel.pipe);
646 processError = QProcess::WriteError;
647 q->setErrorString(QProcess::tr("Error writing to process"));
648#if defined(QPROCESS_DEBUG) && !defined(Q_OS_WINCE)
649 qDebug("QProcessPrivate::canWrite(), failed to write (%s)", strerror(errno));
650#endif
651 emit q->error(processError);
652 return false;
653 }
654
655#if defined QPROCESS_DEBUG
656 qDebug("QProcessPrivate::canWrite(), wrote %d bytes to the process input", int(written));
657#endif
658
659 writeBuffer.free(written);
660 if (!emittedBytesWritten) {
661 emittedBytesWritten = true;
662 emit q->bytesWritten(written);
663 emittedBytesWritten = false;
664 }
665 if (stdinChannel.notifier && !writeBuffer.isEmpty())
666 stdinChannel.notifier->setEnabled(true);
667 if (writeBuffer.isEmpty() && stdinChannel.closed)
668 closeWriteChannel();
669 return true;
670}
671
672/*! \internal
673*/
674bool QProcessPrivate::_q_processDied()
675{
676 Q_Q(QProcess);
677#if defined QPROCESS_DEBUG
678 qDebug("QProcessPrivate::_q_processDied()");
679#endif
680#if defined(Q_OS_UNIX) || defined(Q_OS_OS2)
681 if (!waitForDeadChild())
682 return false;
683#endif
684#ifdef Q_OS_WIN
685 if (processFinishedNotifier)
686 processFinishedNotifier->setEnabled(false);
687#endif
688
689 // the process may have died before it got a chance to report that it was
690 // either running or stopped, so we will call _q_startupNotification() and
691 // give it a chance to emit started() or error(FailedToStart).
692 if (processState == QProcess::Starting) {
693 if (!_q_startupNotification())
694 return true;
695 }
696
697 if (dying) {
698 // at this point we know the process is dead. prevent
699 // reentering this slot recursively by calling waitForFinished()
700 // or opening a dialog inside slots connected to the readyRead
701 // signals emitted below.
702 return true;
703 }
704 dying = true;
705
706 // in case there is data in the pipe line and this slot by chance
707 // got called before the read notifications, call these two slots
708 // so the data is made available before the process dies.
709 _q_canReadStandardOutput();
710 _q_canReadStandardError();
711
712 findExitCode();
713
714 if (crashed) {
715 exitStatus = QProcess::CrashExit;
716 processError = QProcess::Crashed;
717 q->setErrorString(QProcess::tr("Process crashed"));
718 emit q->error(processError);
719 }
720
721 bool wasRunning = (processState == QProcess::Running);
722
723 cleanup();
724
725 if (wasRunning) {
726 // we received EOF now:
727 emit q->readChannelFinished();
728 // in the future:
729 //emit q->standardOutputClosed();
730 //emit q->standardErrorClosed();
731
732 emit q->finished(exitCode);
733 emit q->finished(exitCode, exitStatus);
734 }
735#if defined QPROCESS_DEBUG
736 qDebug("QProcessPrivate::_q_processDied() process is dead");
737#endif
738 return true;
739}
740
741/*! \internal
742*/
743bool QProcessPrivate::_q_startupNotification()
744{
745 Q_Q(QProcess);
746#if defined QPROCESS_DEBUG
747 qDebug("QProcessPrivate::startupNotification()");
748#endif
749
750 if (startupSocketNotifier)
751 startupSocketNotifier->setEnabled(false);
752 if (processStarted()) {
753 q->setProcessState(QProcess::Running);
754 emit q->started();
755 return true;
756 }
757
758 q->setProcessState(QProcess::NotRunning);
759 processError = QProcess::FailedToStart;
760 emit q->error(processError);
761#if defined(Q_OS_UNIX) || defined(Q_OS_OS2)
762 // make sure the process manager removes this entry
763 waitForDeadChild();
764 findExitCode();
765#endif
766 cleanup();
767 return false;
768}
769
770/*! \internal
771*/
772void QProcessPrivate::closeWriteChannel()
773{
774#if defined QPROCESS_DEBUG
775 qDebug("QProcessPrivate::closeWriteChannel()");
776#endif
777 if (stdinChannel.notifier) {
778 extern void qDeleteInEventHandler(QObject *o);
779 stdinChannel.notifier->setEnabled(false);
780 if (stdinChannel.notifier) {
781 qDeleteInEventHandler(stdinChannel.notifier);
782 stdinChannel.notifier = 0;
783 }
784 }
785#ifdef Q_OS_WIN
786 // ### Find a better fix, feeding the process little by little
787 // instead.
788 flushPipeWriter();
789#endif
790 destroyPipe(stdinChannel.pipe);
791}
792
793/*!
794 Constructs a QProcess object with the given \a parent.
795*/
796QProcess::QProcess(QObject *parent)
797 : QIODevice(*new QProcessPrivate, parent)
798{
799#if defined QPROCESS_DEBUG
800 qDebug("QProcess::QProcess(%p)", parent);
801#endif
802}
803
804/*!
805 Destructs the QProcess object, i.e., killing the process.
806
807 Note that this function will not return until the process is
808 terminated.
809*/
810QProcess::~QProcess()
811{
812 Q_D(QProcess);
813 if (d->processState != NotRunning) {
814 qWarning("QProcess: Destroyed while process is still running.");
815 kill();
816 waitForFinished();
817 }
818#if defined(Q_OS_UNIX) || defined(Q_OS_OS2)
819 // make sure the process manager removes this entry
820 d->findExitCode();
821#endif
822 d->cleanup();
823}
824
825/*!
826 \obsolete
827 Returns the read channel mode of the QProcess. This function is
828 equivalent to processChannelMode()
829
830 \sa processChannelMode()
831*/
832QProcess::ProcessChannelMode QProcess::readChannelMode() const
833{
834 return processChannelMode();
835}
836
837/*!
838 \obsolete
839
840 Use setProcessChannelMode(\a mode) instead.
841
842 \sa setProcessChannelMode()
843*/
844void QProcess::setReadChannelMode(ProcessChannelMode mode)
845{
846 setProcessChannelMode(mode);
847}
848
849/*!
850 \since 4.2
851
852 Returns the channel mode of the QProcess standard output and
853 standard error channels.
854
855 \sa setReadChannelMode(), ProcessChannelMode, setReadChannel()
856*/
857QProcess::ProcessChannelMode QProcess::processChannelMode() const
858{
859 Q_D(const QProcess);
860 return d->processChannelMode;
861}
862
863/*!
864 \since 4.2
865
866 Sets the channel mode of the QProcess standard output and standard
867 error channels to the \a mode specified.
868 This mode will be used the next time start() is called. For example:
869
870 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 0
871
872 \sa readChannelMode(), ProcessChannelMode, setReadChannel()
873*/
874void QProcess::setProcessChannelMode(ProcessChannelMode mode)
875{
876 Q_D(QProcess);
877 d->processChannelMode = mode;
878}
879
880/*!
881 Returns the current read channel of the QProcess.
882
883 \sa setReadChannel()
884*/
885QProcess::ProcessChannel QProcess::readChannel() const
886{
887 Q_D(const QProcess);
888 return d->processChannel;
889}
890
891/*!
892 Sets the current read channel of the QProcess to the given \a
893 channel. The current input channel is used by the functions
894 read(), readAll(), readLine(), and getChar(). It also determines
895 which channel triggers QProcess to emit readyRead().
896
897 \sa readChannel()
898*/
899void QProcess::setReadChannel(ProcessChannel channel)
900{
901 Q_D(QProcess);
902 if (d->processChannel != channel) {
903 QByteArray buf = d->buffer.readAll();
904 if (d->processChannel == QProcess::StandardOutput) {
905 for (int i = buf.size() - 1; i >= 0; --i)
906 d->outputReadBuffer.ungetChar(buf.at(i));
907 } else {
908 for (int i = buf.size() - 1; i >= 0; --i)
909 d->errorReadBuffer.ungetChar(buf.at(i));
910 }
911 }
912 d->processChannel = channel;
913}
914
915/*!
916 Closes the read channel \a channel. After calling this function,
917 QProcess will no longer receive data on the channel. Any data that
918 has already been received is still available for reading.
919
920 Call this function to save memory, if you are not interested in
921 the output of the process.
922
923 \sa closeWriteChannel(), setReadChannel()
924*/
925void QProcess::closeReadChannel(ProcessChannel channel)
926{
927 Q_D(QProcess);
928
929 if (channel == StandardOutput)
930 d->stdoutChannel.closed = true;
931 else
932 d->stderrChannel.closed = true;
933}
934
935/*!
936 Schedules the write channel of QProcess to be closed. The channel
937 will close once all data has been written to the process. After
938 calling this function, any attempts to write to the process will
939 fail.
940
941 Closing the write channel is necessary for programs that read
942 input data until the channel has been closed. For example, the
943 program "more" is used to display text data in a console on both
944 Unix and Windows. But it will not display the text data until
945 QProcess's write channel has been closed. Example:
946
947 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 1
948
949 The write channel is implicitly opened when start() is called.
950
951 \sa closeReadChannel()
952*/
953void QProcess::closeWriteChannel()
954{
955 Q_D(QProcess);
956 d->stdinChannel.closed = true; // closing
957 if (d->writeBuffer.isEmpty())
958 d->closeWriteChannel();
959}
960
961/*!
962 \since 4.2
963
964 Redirects the process' standard input to the file indicated by \a
965 fileName. When an input redirection is in place, the QProcess
966 object will be in read-only mode (calling write() will result in
967 error).
968
969 If the file \a fileName does not exist at the moment start() is
970 called or is not readable, starting the process will fail.
971
972 Calling setStandardInputFile() after the process has started has no
973 effect.
974
975 \sa setStandardOutputFile(), setStandardErrorFile(),
976 setStandardOutputProcess()
977*/
978void QProcess::setStandardInputFile(const QString &fileName)
979{
980 Q_D(QProcess);
981 d->stdinChannel = fileName;
982}
983
984/*!
985 \since 4.2
986
987 Redirects the process' standard output to the file \a
988 fileName. When the redirection is in place, the standard output
989 read channel is closed: reading from it using read() will always
990 fail, as will readAllStandardOutput().
991
992 If the file \a fileName doesn't exist at the moment start() is
993 called, it will be created. If it cannot be created, the starting
994 will fail.
995
996 If the file exists and \a mode is QIODevice::Truncate, the file
997 will be truncated. Otherwise (if \a mode is QIODevice::Append),
998 the file will be appended to.
999
1000 Calling setStandardOutputFile() after the process has started has
1001 no effect.
1002
1003 \sa setStandardInputFile(), setStandardErrorFile(),
1004 setStandardOutputProcess()
1005*/
1006void QProcess::setStandardOutputFile(const QString &fileName, OpenMode mode)
1007{
1008 Q_ASSERT(mode == Append || mode == Truncate);
1009 Q_D(QProcess);
1010
1011 d->stdoutChannel = fileName;
1012 d->stdoutChannel.append = mode == Append;
1013}
1014
1015/*!
1016 \since 4.2
1017
1018 Redirects the process' standard error to the file \a
1019 fileName. When the redirection is in place, the standard error
1020 read channel is closed: reading from it using read() will always
1021 fail, as will readAllStandardError(). The file will be appended to
1022 if \a mode is Append, otherwise, it will be truncated.
1023
1024 See setStandardOutputFile() for more information on how the file
1025 is opened.
1026
1027 Note: if setProcessChannelMode() was called with an argument of
1028 QProcess::MergedChannels, this function has no effect.
1029
1030 \sa setStandardInputFile(), setStandardOutputFile(),
1031 setStandardOutputProcess()
1032*/
1033void QProcess::setStandardErrorFile(const QString &fileName, OpenMode mode)
1034{
1035 Q_ASSERT(mode == Append || mode == Truncate);
1036 Q_D(QProcess);
1037
1038 d->stderrChannel = fileName;
1039 d->stderrChannel.append = mode == Append;
1040}
1041
1042/*!
1043 \since 4.2
1044
1045 Pipes the standard output stream of this process to the \a
1046 destination process' standard input.
1047
1048 The following shell command:
1049 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 2
1050
1051 Can be accomplished with QProcesses with the following code:
1052 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 3
1053*/
1054void QProcess::setStandardOutputProcess(QProcess *destination)
1055{
1056 QProcessPrivate *dfrom = d_func();
1057 QProcessPrivate *dto = destination->d_func();
1058 dfrom->stdoutChannel.pipeTo(dto);
1059 dto->stdinChannel.pipeFrom(dfrom);
1060}
1061
1062/*!
1063 If QProcess has been assigned a working directory, this function returns
1064 the working directory that the QProcess will enter before the program has
1065 started. Otherwise, (i.e., no directory has been assigned,) an empty
1066 string is returned, and QProcess will use the application's current
1067 working directory instead.
1068
1069 \sa setWorkingDirectory()
1070*/
1071QString QProcess::workingDirectory() const
1072{
1073 Q_D(const QProcess);
1074 return d->workingDirectory;
1075}
1076
1077/*!
1078 Sets the working directory to \a dir. QProcess will start the
1079 process in this directory. The default behavior is to start the
1080 process in the working directory of the calling process.
1081
1082 \sa workingDirectory(), start()
1083*/
1084void QProcess::setWorkingDirectory(const QString &dir)
1085{
1086 Q_D(QProcess);
1087 d->workingDirectory = dir;
1088}
1089
1090/*!
1091 Returns the native process identifier for the running process, if
1092 available. If no process is currently running, 0 is returned.
1093*/
1094Q_PID QProcess::pid() const
1095{
1096 Q_D(const QProcess);
1097 return d->pid;
1098}
1099
1100/*! \reimp
1101
1102 This function operates on the current read channel.
1103
1104 \sa readChannel(), setReadChannel()
1105*/
1106bool QProcess::canReadLine() const
1107{
1108 Q_D(const QProcess);
1109 const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1110 ? &d->errorReadBuffer
1111 : &d->outputReadBuffer;
1112 return readBuffer->canReadLine() || QIODevice::canReadLine();
1113}
1114
1115/*!
1116 Closes all communication with the process and kills it. After calling this
1117 function, QProcess will no longer emit readyRead(), and data can no
1118 longer be read or written.
1119*/
1120void QProcess::close()
1121{
1122 emit aboutToClose();
1123 while (waitForBytesWritten(-1))
1124 ;
1125 kill();
1126 waitForFinished(-1);
1127 QIODevice::close();
1128}
1129
1130/*! \reimp
1131
1132 Returns true if the process is not running, and no more data is available
1133 for reading; otherwise returns false.
1134*/
1135bool QProcess::atEnd() const
1136{
1137 Q_D(const QProcess);
1138 const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1139 ? &d->errorReadBuffer
1140 : &d->outputReadBuffer;
1141 return QIODevice::atEnd() && (!isOpen() || readBuffer->isEmpty());
1142}
1143
1144/*! \reimp
1145*/
1146bool QProcess::isSequential() const
1147{
1148 return true;
1149}
1150
1151/*! \reimp
1152*/
1153qint64 QProcess::bytesAvailable() const
1154{
1155 Q_D(const QProcess);
1156 const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1157 ? &d->errorReadBuffer
1158 : &d->outputReadBuffer;
1159#if defined QPROCESS_DEBUG
1160 qDebug("QProcess::bytesAvailable() == %i (%s)", readBuffer->size(),
1161 (d->processChannel == QProcess::StandardError) ? "stderr" : "stdout");
1162#endif
1163 return readBuffer->size() + QIODevice::bytesAvailable();
1164}
1165
1166/*! \reimp
1167*/
1168qint64 QProcess::bytesToWrite() const
1169{
1170 Q_D(const QProcess);
1171 qint64 size = d->writeBuffer.size();
1172#ifdef Q_OS_WIN
1173 size += d->pipeWriterBytesToWrite();
1174#endif
1175 return size;
1176}
1177
1178/*!
1179 Returns the type of error that occurred last.
1180
1181 \sa state()
1182*/
1183QProcess::ProcessError QProcess::error() const
1184{
1185 Q_D(const QProcess);
1186 return d->processError;
1187}
1188
1189/*!
1190 Returns the current state of the process.
1191
1192 \sa stateChanged(), error()
1193*/
1194QProcess::ProcessState QProcess::state() const
1195{
1196 Q_D(const QProcess);
1197 return d->processState;
1198}
1199
1200/*!
1201 Sets the environment that QProcess will use when starting a process to the
1202 \a environment specified which consists of a list of key=value pairs.
1203
1204 For example, the following code adds the \c{C:\\BIN} directory to the list of
1205 executable paths (\c{PATHS}) on Windows:
1206
1207 \snippet doc/src/snippets/qprocess-environment/main.cpp 0
1208
1209 \sa environment(), systemEnvironment()
1210*/
1211void QProcess::setEnvironment(const QStringList &environment)
1212{
1213 Q_D(QProcess);
1214 d->environment = environment;
1215}
1216
1217/*!
1218 Returns the environment that QProcess will use when starting a
1219 process, or an empty QStringList if no environment has been set
1220 using setEnvironment(). If no environment has been set, the
1221 environment of the calling process will be used.
1222
1223 \note The environment settings are ignored on Windows CE,
1224 as there is no concept of an environment.
1225
1226 \sa setEnvironment(), systemEnvironment()
1227*/
1228QStringList QProcess::environment() const
1229{
1230 Q_D(const QProcess);
1231 return d->environment;
1232}
1233
1234/*!
1235 Blocks until the process has started and the started() signal has
1236 been emitted, or until \a msecs milliseconds have passed.
1237
1238 Returns true if the process was started successfully; otherwise
1239 returns false (if the operation timed out or if an error
1240 occurred).
1241
1242 This function can operate without an event loop. It is
1243 useful when writing non-GUI applications and when performing
1244 I/O operations in a non-GUI thread.
1245
1246 \warning Calling this function from the main (GUI) thread
1247 might cause your user interface to freeze.
1248
1249 If msecs is -1, this function will not time out.
1250
1251 \sa started(), waitForReadyRead(), waitForBytesWritten(), waitForFinished()
1252*/
1253bool QProcess::waitForStarted(int msecs)
1254{
1255 Q_D(QProcess);
1256 if (d->processState == QProcess::Starting) {
1257 if (!d->waitForStarted(msecs))
1258 return false;
1259 setProcessState(QProcess::Running);
1260 emit started();
1261 }
1262 return d->processState == QProcess::Running;
1263}
1264
1265/*! \reimp
1266*/
1267bool QProcess::waitForReadyRead(int msecs)
1268{
1269 Q_D(QProcess);
1270
1271 if (d->processState == QProcess::NotRunning)
1272 return false;
1273 if (d->processChannel == QProcess::StandardOutput && d->stdoutChannel.closed)
1274 return false;
1275 if (d->processChannel == QProcess::StandardError && d->stderrChannel.closed)
1276 return false;
1277 return d->waitForReadyRead(msecs);
1278}
1279
1280/*! \reimp
1281*/
1282bool QProcess::waitForBytesWritten(int msecs)
1283{
1284 Q_D(QProcess);
1285 if (d->processState == QProcess::NotRunning)
1286 return false;
1287 if (d->processState == QProcess::Starting) {
1288 QTime stopWatch;
1289 stopWatch.start();
1290 bool started = waitForStarted(msecs);
1291 if (!started)
1292 return false;
1293 if (msecs != -1)
1294 msecs -= stopWatch.elapsed();
1295 }
1296
1297 return d->waitForBytesWritten(msecs);
1298}
1299
1300/*!
1301 Blocks until the process has finished and the finished() signal
1302 has been emitted, or until \a msecs milliseconds have passed.
1303
1304 Returns true if the process finished; otherwise returns false (if
1305 the operation timed out or if an error occurred).
1306
1307 This function can operate without an event loop. It is
1308 useful when writing non-GUI applications and when performing
1309 I/O operations in a non-GUI thread.
1310
1311 \warning Calling this function from the main (GUI) thread
1312 might cause your user interface to freeze.
1313
1314 If msecs is -1, this function will not time out.
1315
1316 \sa finished(), waitForStarted(), waitForReadyRead(), waitForBytesWritten()
1317*/
1318bool QProcess::waitForFinished(int msecs)
1319{
1320 Q_D(QProcess);
1321 if (d->processState == QProcess::NotRunning)
1322 return false;
1323 if (d->processState == QProcess::Starting) {
1324 QTime stopWatch;
1325 stopWatch.start();
1326 bool started = waitForStarted(msecs);
1327 if (!started)
1328 return false;
1329 if (msecs != -1)
1330 msecs -= stopWatch.elapsed();
1331 }
1332
1333 return d->waitForFinished(msecs);
1334}
1335
1336/*!
1337 Sets the current state of the QProcess to the \a state specified.
1338
1339 \sa state()
1340*/
1341void QProcess::setProcessState(ProcessState state)
1342{
1343 Q_D(QProcess);
1344 if (d->processState == state)
1345 return;
1346 d->processState = state;
1347 emit stateChanged(state);
1348}
1349
1350/*!
1351 This function is called in the child process context just before the
1352 program is executed on Unix or Mac OS X (i.e., after \e fork(), but before
1353 \e execve()). Reimplement this function to do last minute initialization
1354 of the child process. Example:
1355
1356 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 4
1357
1358 You cannot exit the process (by calling exit(), for instance) from
1359 this function. If you need to stop the program before it starts
1360 execution, your workaround is to emit finished() and then call
1361 exit().
1362
1363 \warning This function is called by QProcess on Unix and Mac OS X
1364 only. On Windows, it is not called.
1365*/
1366void QProcess::setupChildProcess()
1367{
1368}
1369
1370/*! \reimp
1371*/
1372qint64 QProcess::readData(char *data, qint64 maxlen)
1373{
1374 Q_D(QProcess);
1375 QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1376 ? &d->errorReadBuffer
1377 : &d->outputReadBuffer;
1378
1379 if (maxlen == 1 && !readBuffer->isEmpty()) {
1380 int c = readBuffer->getChar();
1381 if (c == -1) {
1382#if defined QPROCESS_DEBUG
1383 qDebug("QProcess::readData(%p \"%s\", %d) == -1",
1384 data, qt_prettyDebug(data, 1, maxlen).constData(), 1);
1385#endif
1386 return -1;
1387 }
1388 *data = (char) c;
1389#if defined QPROCESS_DEBUG
1390 qDebug("QProcess::readData(%p \"%s\", %d) == 1",
1391 data, qt_prettyDebug(data, 1, maxlen).constData(), 1);
1392#endif
1393 return 1;
1394 }
1395
1396 qint64 bytesToRead = qint64(qMin(readBuffer->size(), (int)maxlen));
1397 qint64 readSoFar = 0;
1398 while (readSoFar < bytesToRead) {
1399 const char *ptr = readBuffer->readPointer();
1400 int bytesToReadFromThisBlock = qMin<qint64>(bytesToRead - readSoFar,
1401 readBuffer->nextDataBlockSize());
1402 memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
1403 readSoFar += bytesToReadFromThisBlock;
1404 readBuffer->free(bytesToReadFromThisBlock);
1405 }
1406
1407#if defined QPROCESS_DEBUG
1408 qDebug("QProcess::readData(%p \"%s\", %lld) == %lld",
1409 data, qt_prettyDebug(data, readSoFar, 16).constData(), maxlen, readSoFar);
1410#endif
1411 if (!readSoFar && d->processState == QProcess::NotRunning)
1412 return -1; // EOF
1413 return readSoFar;
1414}
1415
1416/*! \reimp
1417*/
1418qint64 QProcess::writeData(const char *data, qint64 len)
1419{
1420 Q_D(QProcess);
1421
1422#if defined(Q_OS_WINCE)
1423 Q_UNUSED(data);
1424 Q_UNUSED(len);
1425 d->processError = QProcess::WriteError;
1426 setErrorString(tr("Error writing to process"));
1427 emit error(d->processError);
1428 return -1;
1429#endif
1430
1431 if (d->stdinChannel.closed) {
1432#if defined QPROCESS_DEBUG
1433 qDebug("QProcess::writeData(%p \"%s\", %lld) == 0 (write channel closing)",
1434 data, qt_prettyDebug(data, len, 16).constData(), len);
1435#endif
1436 return 0;
1437 }
1438
1439 if (len == 1) {
1440 d->writeBuffer.putChar(*data);
1441 if (d->stdinChannel.notifier)
1442 d->stdinChannel.notifier->setEnabled(true);
1443#if defined QPROCESS_DEBUG
1444 qDebug("QProcess::writeData(%p \"%s\", %lld) == 1 (written to buffer)",
1445 data, qt_prettyDebug(data, len, 16).constData(), len);
1446#endif
1447#if defined(Q_OS_OS2)
1448 qint64 available = d->bytesAvailableInStdin();
1449 if (available > 0)
1450 d->_q_canWrite();
1451#endif
1452 return 1;
1453 }
1454
1455 char *dest = d->writeBuffer.reserve(len);
1456 memcpy(dest, data, len);
1457 if (d->stdinChannel.notifier)
1458 d->stdinChannel.notifier->setEnabled(true);
1459#if defined QPROCESS_DEBUG
1460 qDebug("QProcess::writeData(%p \"%s\", %lld) == %lld (written to buffer)",
1461 data, qt_prettyDebug(data, len, 16).constData(), len, len);
1462#endif
1463#if defined(Q_OS_OS2)
1464 qint64 available = d->bytesAvailableInStdin();
1465 if (available > 0)
1466 d->_q_canWrite();
1467#endif
1468 return len;
1469}
1470
1471/*!
1472 Regardless of the current read channel, this function returns all
1473 data available from the standard output of the process as a
1474 QByteArray.
1475
1476 \sa readyReadStandardOutput(), readAllStandardError(), readChannel(), setReadChannel()
1477*/
1478QByteArray QProcess::readAllStandardOutput()
1479{
1480 ProcessChannel tmp = readChannel();
1481 setReadChannel(StandardOutput);
1482 QByteArray data = readAll();
1483 setReadChannel(tmp);
1484 return data;
1485}
1486
1487/*!
1488 Regardless of the current read channel, this function returns all
1489 data available from the standard error of the process as a
1490 QByteArray.
1491
1492 \sa readyReadStandardError(), readAllStandardOutput(), readChannel(), setReadChannel()
1493*/
1494QByteArray QProcess::readAllStandardError()
1495{
1496 ProcessChannel tmp = readChannel();
1497 setReadChannel(StandardError);
1498 QByteArray data = readAll();
1499 setReadChannel(tmp);
1500 return data;
1501}
1502
1503/*!
1504 Starts the program \a program in a new process, if one is not already
1505 running, passing the command line arguments in \a arguments. The OpenMode
1506 is set to \a mode.
1507
1508 The QProcess object will immediately enter the Starting state. If the
1509 process starts successfully, QProcess will emit started(); otherwise,
1510 error() will be emitted. If the QProcess object is already running a
1511 process, a warning may be printed at the console, and the existing
1512 process will continue running.
1513
1514 Note that arguments that contain spaces are not passed to the
1515 process as separate arguments.
1516
1517 \bold{Windows:} Arguments that contain spaces are wrapped in quotes.
1518
1519 \note Processes are started asynchronously, which means the started()
1520 and error() signals may be delayed. Call waitForStarted() to make
1521 sure the process has started (or has failed to start) and those signals
1522 have been emitted.
1523
1524 \sa pid(), started(), waitForStarted()
1525*/
1526void QProcess::start(const QString &program, const QStringList &arguments, OpenMode mode)
1527{
1528 Q_D(QProcess);
1529 if (d->processState != NotRunning) {
1530 qWarning("QProcess::start: Process is already running");
1531 return;
1532 }
1533
1534#if defined QPROCESS_DEBUG
1535 qDebug() << "QProcess::start(" << program << "," << arguments << "," << mode << ")";
1536#endif
1537
1538 d->outputReadBuffer.clear();
1539 d->errorReadBuffer.clear();
1540
1541 if (d->stdinChannel.type != QProcessPrivate::Channel::Normal)
1542 mode &= ~WriteOnly; // not open for writing
1543 if (d->stdoutChannel.type != QProcessPrivate::Channel::Normal &&
1544 (d->stderrChannel.type != QProcessPrivate::Channel::Normal ||
1545 d->processChannelMode == MergedChannels))
1546 mode &= ~ReadOnly; // not open for reading
1547 if (mode == 0)
1548 mode = Unbuffered;
1549 QIODevice::open(mode);
1550
1551 d->stdinChannel.closed = false;
1552 d->stdoutChannel.closed = false;
1553 d->stderrChannel.closed = false;
1554
1555 d->program = program;
1556 d->arguments = arguments;
1557
1558 d->exitCode = 0;
1559 d->exitStatus = NormalExit;
1560 d->processError = QProcess::UnknownError;
1561 d->errorString.clear();
1562 d->startProcess();
1563}
1564
1565
1566static QStringList parseCombinedArgString(const QString &program)
1567{
1568 QStringList args;
1569 QString tmp;
1570 int quoteCount = 0;
1571 bool inQuote = false;
1572
1573 // handle quoting. tokens can be surrounded by double quotes
1574 // "hello world". three consecutive double quotes represent
1575 // the quote character itself.
1576 for (int i = 0; i < program.size(); ++i) {
1577 if (program.at(i) == QLatin1Char('"')) {
1578 ++quoteCount;
1579 if (quoteCount == 3) {
1580 // third consecutive quote
1581 quoteCount = 0;
1582 tmp += program.at(i);
1583 }
1584 continue;
1585 }
1586 if (quoteCount) {
1587 if (quoteCount == 1)
1588 inQuote = !inQuote;
1589 quoteCount = 0;
1590 }
1591 if (!inQuote && program.at(i).isSpace()) {
1592 if (!tmp.isEmpty()) {
1593 args += tmp;
1594 tmp.clear();
1595 }
1596 } else {
1597 tmp += program.at(i);
1598 }
1599 }
1600 if (!tmp.isEmpty())
1601 args += tmp;
1602
1603 return args;
1604}
1605
1606/*!
1607 \overload
1608
1609 Starts the program \a program in a new process, if one is not already
1610 running. \a program is a single string of text containing both the
1611 program name and its arguments. The arguments are separated by one or
1612 more spaces. For example:
1613
1614 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 5
1615
1616 The \a program string can also contain quotes, to ensure that arguments
1617 containing spaces are correctly supplied to the new process. For example:
1618
1619 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 6
1620
1621 If the QProcess object is already running a process, a warning may be
1622 printed at the console, and the existing process will continue running.
1623
1624 Note that, on Windows, quotes need to be both escaped and quoted.
1625 For example, the above code would be specified in the following
1626 way to ensure that \c{"My Documents"} is used as the argument to
1627 the \c dir executable:
1628
1629 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 7
1630
1631 The OpenMode is set to \a mode.
1632*/
1633void QProcess::start(const QString &program, OpenMode mode)
1634{
1635 QStringList args = parseCombinedArgString(program);
1636 if (args.isEmpty()) {
1637 Q_D(QProcess);
1638 d->processError = QProcess::FailedToStart;
1639 setErrorString(tr("No program defined"));
1640 emit error(d->processError);
1641 return;
1642 }
1643
1644 QString prog = args.first();
1645 args.removeFirst();
1646
1647 start(prog, args, mode);
1648}
1649
1650/*!
1651 Attempts to terminate the process.
1652
1653 The process may not exit as a result of calling this function (it is given
1654 the chance to prompt the user for any unsaved files, etc).
1655
1656 On Windows, terminate() posts a WM_CLOSE message to all toplevel windows
1657 of the process and then to the main thread of the process itself. On Unix
1658 and Mac OS X the SIGTERM signal is sent.
1659
1660 Console applications on Windows that do not run an event loop, or whose
1661 event loop does not handle the WM_CLOSE message, can only be terminated by
1662 calling kill().
1663
1664 \sa kill()
1665*/
1666void QProcess::terminate()
1667{
1668 Q_D(QProcess);
1669 d->terminateProcess();
1670}
1671
1672/*!
1673 Kills the current process, causing it to exit immediately.
1674
1675 On Windows, kill() uses TerminateProcess, and on Unix and Mac OS X, the
1676 SIGKILL signal is sent to the process.
1677
1678 \sa terminate()
1679*/
1680void QProcess::kill()
1681{
1682 Q_D(QProcess);
1683 d->killProcess();
1684}
1685
1686/*!
1687 Returns the exit code of the last process that finished.
1688*/
1689int QProcess::exitCode() const
1690{
1691 Q_D(const QProcess);
1692 return d->exitCode;
1693}
1694
1695/*!
1696 \since 4.1
1697
1698 Returns the exit status of the last process that finished.
1699
1700 On Windows, if the process was terminated with TerminateProcess()
1701 from another application this function will still return NormalExit
1702 unless the exit code is less than 0.
1703*/
1704QProcess::ExitStatus QProcess::exitStatus() const
1705{
1706 Q_D(const QProcess);
1707 return d->exitStatus;
1708}
1709
1710/*!
1711 Starts the program \a program with the arguments \a arguments in a
1712 new process, waits for it to finish, and then returns the exit
1713 code of the process. Any data the new process writes to the
1714 console is forwarded to the calling process.
1715
1716 The environment and working directory are inherited by the calling
1717 process.
1718
1719 On Windows, arguments that contain spaces are wrapped in quotes.
1720*/
1721int QProcess::execute(const QString &program, const QStringList &arguments)
1722{
1723 QProcess process;
1724 process.setReadChannelMode(ForwardedChannels);
1725 process.start(program, arguments);
1726 process.waitForFinished(-1);
1727 return process.exitCode();
1728}
1729
1730/*!
1731 \overload
1732
1733 Starts the program \a program in a new process. \a program is a
1734 single string of text containing both the program name and its
1735 arguments. The arguments are separated by one or more spaces.
1736*/
1737int QProcess::execute(const QString &program)
1738{
1739 QProcess process;
1740 process.setReadChannelMode(ForwardedChannels);
1741 process.start(program);
1742 process.waitForFinished(-1);
1743 return process.exitCode();
1744}
1745
1746/*!
1747 Starts the program \a program with the arguments \a arguments in a
1748 new process, and detaches from it. Returns true on success;
1749 otherwise returns false. If the calling process exits, the
1750 detached process will continue to live.
1751
1752 Note that arguments that contain spaces are not passed to the
1753 process as separate arguments.
1754
1755 \bold{Unix:} The started process will run in its own session and act
1756 like a daemon.
1757
1758 \bold{Windows:} Arguments that contain spaces are wrapped in quotes.
1759 The started process will run as a regular standalone process.
1760
1761 The process will be started in the directory \a workingDirectory.
1762
1763 If the function is successful then *\a pid is set to the process
1764 identifier of the started process.
1765*/
1766bool QProcess::startDetached(const QString &program,
1767 const QStringList &arguments,
1768 const QString &workingDirectory,
1769 qint64 *pid)
1770{
1771 return QProcessPrivate::startDetached(program,
1772 arguments,
1773 workingDirectory,
1774 pid);
1775}
1776
1777/*!
1778 Starts the program \a program with the given \a arguments in a
1779 new process, and detaches from it. Returns true on success;
1780 otherwise returns false. If the calling process exits, the
1781 detached process will continue to live.
1782
1783 Note that arguments that contain spaces are not passed to the
1784 process as separate arguments.
1785
1786 \bold{Unix:} The started process will run in its own session and act
1787 like a daemon.
1788
1789 \bold{Windows:} Arguments that contain spaces are wrapped in quotes.
1790 The started process will run as a regular standalone process.
1791*/
1792bool QProcess::startDetached(const QString &program,
1793 const QStringList &arguments)
1794{
1795 return QProcessPrivate::startDetached(program, arguments);
1796}
1797
1798/*!
1799 \overload
1800
1801 Starts the program \a program in a new process. \a program is a
1802 single string of text containing both the program name and its
1803 arguments. The arguments are separated by one or more spaces.
1804
1805 The \a program string can also contain quotes, to ensure that arguments
1806 containing spaces are correctly supplied to the new process.
1807*/
1808bool QProcess::startDetached(const QString &program)
1809{
1810 QStringList args = parseCombinedArgString(program);
1811 if (args.isEmpty())
1812 return false;
1813
1814 QString prog = args.first();
1815 args.removeFirst();
1816
1817 return QProcessPrivate::startDetached(prog, args);
1818}
1819
1820QT_BEGIN_INCLUDE_NAMESPACE
1821#ifdef Q_OS_MAC
1822# include <crt_externs.h>
1823# define environ (*_NSGetEnviron())
1824#elif defined(Q_OS_WINCE)
1825 static char *qt_wince_environ[] = { 0 };
1826#define environ qt_wince_environ
1827#elif !defined(Q_OS_WIN)
1828 extern char **environ;
1829#endif
1830QT_END_INCLUDE_NAMESPACE
1831
1832/*!
1833 \since 4.1
1834
1835 Returns the environment of the calling process as a list of
1836 key=value pairs. Example:
1837
1838 \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 8
1839
1840 \sa environment(), setEnvironment()
1841*/
1842QStringList QProcess::systemEnvironment()
1843{
1844 QStringList tmp;
1845 char *entry = 0;
1846 int count = 0;
1847 while ((entry = environ[count++]))
1848 tmp << QString::fromLocal8Bit(entry);
1849 return tmp;
1850}
1851
1852/*!
1853 \typedef Q_PID
1854 \relates QProcess
1855
1856 Typedef for the identifiers used to represent processes on the underlying
1857 platform. On Unix, this corresponds to \l qint64; on Windows, it
1858 corresponds to \c{_PROCESS_INFORMATION*}.
1859
1860 \sa QProcess::pid()
1861*/
1862
1863QT_END_NAMESPACE
1864
1865#include "moc_qprocess.cpp"
1866
1867#endif // QT_NO_PROCESS
1868
Note: See TracBrowser for help on using the repository browser.