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