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
|
# -*- test-case-name: twisted.test.test_process -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
UNIX Process management.
Do NOT use this module directly - use reactor.spawnProcess() instead.
Maintainer: Itamar Shtull-Trauring
"""
from __future__ import division, absolute_import, print_function
from twisted.python.runtime import platform
if platform.isWindows():
raise ImportError(("twisted.internet.process does not work on Windows. "
"Use the reactor.spawnProcess() API instead."))
import errno
import gc
import os
import io
import signal
import stat
import sys
import traceback
try:
import pty
except ImportError:
pty = None
try:
import fcntl, termios
except ImportError:
fcntl = None
from zope.interface import implementer
from twisted.python import log, failure
from twisted.python.util import switchUID
from twisted.python.compat import items, range, _PY3
from twisted.internet import fdesc, abstract, error
from twisted.internet.main import CONNECTION_LOST, CONNECTION_DONE
from twisted.internet._baseprocess import BaseProcess
from twisted.internet.interfaces import IProcessTransport
# Some people were importing this, which is incorrect, just keeping it
# here for backwards compatibility:
ProcessExitedAlready = error.ProcessExitedAlready
reapProcessHandlers = {}
def reapAllProcesses():
"""
Reap all registered processes.
"""
# Coerce this to a list, as reaping the process changes the dictionary and
# causes a "size changed during iteration" exception
for process in list(reapProcessHandlers.values()):
process.reapProcess()
def registerReapProcessHandler(pid, process):
"""
Register a process handler for the given pid, in case L{reapAllProcesses}
is called.
@param pid: the pid of the process.
@param process: a process handler.
"""
if pid in reapProcessHandlers:
raise RuntimeError("Try to register an already registered process.")
try:
auxPID, status = os.waitpid(pid, os.WNOHANG)
except:
log.msg('Failed to reap %d:' % pid)
log.err()
auxPID = None
if auxPID:
process.processEnded(status)
else:
# if auxPID is 0, there are children but none have exited
reapProcessHandlers[pid] = process
def unregisterReapProcessHandler(pid, process):
"""
Unregister a process handler previously registered with
L{registerReapProcessHandler}.
"""
if not (pid in reapProcessHandlers
and reapProcessHandlers[pid] == process):
raise RuntimeError("Try to unregister a process not registered.")
del reapProcessHandlers[pid]
class ProcessWriter(abstract.FileDescriptor):
"""
(Internal) Helper class to write into a Process's input pipe.
I am a helper which describes a selectable asynchronous writer to a
process's input pipe, including stdin.
@ivar enableReadHack: A flag which determines how readability on this
write descriptor will be handled. If C{True}, then readability may
indicate the reader for this write descriptor has been closed (ie,
the connection has been lost). If C{False}, then readability events
are ignored.
"""
connected = 1
ic = 0
enableReadHack = False
def __init__(self, reactor, proc, name, fileno, forceReadHack=False):
"""
Initialize, specifying a Process instance to connect to.
"""
abstract.FileDescriptor.__init__(self, reactor)
fdesc.setNonBlocking(fileno)
self.proc = proc
self.name = name
self.fd = fileno
if not stat.S_ISFIFO(os.fstat(self.fileno()).st_mode):
# If the fd is not a pipe, then the read hack is never
# applicable. This case arises when ProcessWriter is used by
# StandardIO and stdout is redirected to a normal file.
self.enableReadHack = False
elif forceReadHack:
self.enableReadHack = True
else:
# Detect if this fd is actually a write-only fd. If it's
# valid to read, don't try to detect closing via read.
# This really only means that we cannot detect a TTY's write
# pipe being closed.
try:
os.read(self.fileno(), 0)
except OSError:
# It's a write-only pipe end, enable hack
self.enableReadHack = True
if self.enableReadHack:
self.startReading()
def fileno(self):
"""
Return the fileno() of my process's stdin.
"""
return self.fd
def writeSomeData(self, data):
"""
Write some data to the open process.
"""
rv = fdesc.writeToFD(self.fd, data)
if rv == len(data) and self.enableReadHack:
# If the send buffer is now empty and it is necessary to monitor
# this descriptor for readability to detect close, try detecting
# readability now.
self.startReading()
return rv
def write(self, data):
self.stopReading()
abstract.FileDescriptor.write(self, data)
def doRead(self):
"""
The only way a write pipe can become "readable" is at EOF, because the
child has closed it, and we're using a reactor which doesn't
distinguish between readable and closed (such as the select reactor).
Except that's not true on linux < 2.6.11. It has the following
characteristics: write pipe is completely empty => POLLOUT (writable in
select), write pipe is not completely empty => POLLIN (readable in
select), write pipe's reader closed => POLLIN|POLLERR (readable and
writable in select)
That's what this funky code is for. If linux was not broken, this
function could be simply "return CONNECTION_LOST".
"""
if self.enableReadHack:
return CONNECTION_LOST
else:
self.stopReading()
def connectionLost(self, reason):
"""
See abstract.FileDescriptor.connectionLost.
"""
# At least on macOS 10.4, exiting while stdout is non-blocking can
# result in data loss. For some reason putting the file descriptor
# back into blocking mode seems to resolve this issue.
fdesc.setBlocking(self.fd)
abstract.FileDescriptor.connectionLost(self, reason)
self.proc.childConnectionLost(self.name, reason)
class ProcessReader(abstract.FileDescriptor):
"""
ProcessReader
I am a selectable representation of a process's output pipe, such as
stdout and stderr.
"""
connected = True
def __init__(self, reactor, proc, name, fileno):
"""
Initialize, specifying a process to connect to.
"""
abstract.FileDescriptor.__init__(self, reactor)
fdesc.setNonBlocking(fileno)
self.proc = proc
self.name = name
self.fd = fileno
self.startReading()
def fileno(self):
"""
Return the fileno() of my process's stderr.
"""
return self.fd
def writeSomeData(self, data):
# the only time this is actually called is after .loseConnection Any
# actual write attempt would fail, so we must avoid that. This hack
# allows us to use .loseConnection on both readers and writers.
assert data == b""
return CONNECTION_LOST
def doRead(self):
"""
This is called when the pipe becomes readable.
"""
return fdesc.readFromFD(self.fd, self.dataReceived)
def dataReceived(self, data):
self.proc.childDataReceived(self.name, data)
def loseConnection(self):
if self.connected and not self.disconnecting:
self.disconnecting = 1
self.stopReading()
self.reactor.callLater(0, self.connectionLost,
failure.Failure(CONNECTION_DONE))
def connectionLost(self, reason):
"""
Close my end of the pipe, signal the Process (which signals the
ProcessProtocol).
"""
abstract.FileDescriptor.connectionLost(self, reason)
self.proc.childConnectionLost(self.name, reason)
class _BaseProcess(BaseProcess, object):
"""
Base class for Process and PTYProcess.
"""
status = None
pid = None
def reapProcess(self):
"""
Try to reap a process (without blocking) via waitpid.
This is called when sigchild is caught or a Process object loses its
"connection" (stdout is closed) This ought to result in reaping all
zombie processes, since it will be called twice as often as it needs
to be.
(Unfortunately, this is a slightly experimental approach, since
UNIX has no way to be really sure that your process is going to
go away w/o blocking. I don't want to block.)
"""
try:
try:
pid, status = os.waitpid(self.pid, os.WNOHANG)
except OSError as e:
if e.errno == errno.ECHILD:
# no child process
pid = None
else:
raise
except:
log.msg('Failed to reap %d:' % self.pid)
log.err()
pid = None
if pid:
self.processEnded(status)
unregisterReapProcessHandler(pid, self)
def _getReason(self, status):
exitCode = sig = None
if os.WIFEXITED(status):
exitCode = os.WEXITSTATUS(status)
else:
sig = os.WTERMSIG(status)
if exitCode or sig:
return error.ProcessTerminated(exitCode, sig, status)
return error.ProcessDone(status)
def signalProcess(self, signalID):
"""
Send the given signal C{signalID} to the process. It'll translate a
few signals ('HUP', 'STOP', 'INT', 'KILL', 'TERM') from a string
representation to its int value, otherwise it'll pass directly the
value provided
@type signalID: C{str} or C{int}
"""
if signalID in ('HUP', 'STOP', 'INT', 'KILL', 'TERM'):
signalID = getattr(signal, 'SIG%s' % (signalID,))
if self.pid is None:
raise ProcessExitedAlready()
try:
os.kill(self.pid, signalID)
except OSError as e:
if e.errno == errno.ESRCH:
raise ProcessExitedAlready()
else:
raise
def _resetSignalDisposition(self):
# The Python interpreter ignores some signals, and our child
# process will inherit that behaviour. To have a child process
# that responds to signals normally, we need to reset our
# child process's signal handling (just) after we fork and
# before we execvpe.
for signalnum in range(1, signal.NSIG):
if signal.getsignal(signalnum) == signal.SIG_IGN:
# Reset signal handling to the default
signal.signal(signalnum, signal.SIG_DFL)
def _fork(self, path, uid, gid, executable, args, environment, **kwargs):
"""
Fork and then exec sub-process.
@param path: the path where to run the new process.
@type path: L{bytes} or L{unicode}
@param uid: if defined, the uid used to run the new process.
@type uid: L{int}
@param gid: if defined, the gid used to run the new process.
@type gid: L{int}
@param executable: the executable to run in a new process.
@type executable: L{str}
@param args: arguments used to create the new process.
@type args: L{list}.
@param environment: environment used for the new process.
@type environment: L{dict}.
@param kwargs: keyword arguments to L{_setupChild} method.
"""
collectorEnabled = gc.isenabled()
gc.disable()
try:
self.pid = os.fork()
except:
# Still in the parent process
if collectorEnabled:
gc.enable()
raise
else:
if self.pid == 0:
# A return value of 0 from fork() indicates that we are now
# executing in the child process.
# Do not put *ANY* code outside the try block. The child
# process must either exec or _exit. If it gets outside this
# block (due to an exception that is not handled here, but
# which might be handled higher up), there will be two copies
# of the parent running in parallel, doing all kinds of damage.
# After each change to this code, review it to make sure there
# are no exit paths.
try:
# Stop debugging. If I am, I don't care anymore.
sys.settrace(None)
self._setupChild(**kwargs)
self._execChild(path, uid, gid, executable, args,
environment)
except:
# If there are errors, try to write something descriptive
# to stderr before exiting.
# The parent's stderr isn't *necessarily* fd 2 anymore, or
# even still available; however, even libc assumes that
# write(2, err) is a useful thing to attempt.
try:
stderr = os.fdopen(2, 'wb')
msg = ("Upon execvpe {0} {1} in environment id {2}"
"\n:").format(executable, str(args),
id(environment))
if _PY3:
# On Python 3, print_exc takes a text stream, but
# on Python 2 it still takes a byte stream. So on
# Python 3 we will wrap up the byte stream returned
# by os.fdopen using TextIOWrapper.
# We hard-code UTF-8 as the encoding here, rather
# than looking at something like
# getfilesystemencoding() or sys.stderr.encoding,
# because we want an encoding that will be able to
# encode the full range of code points. We are
# (most likely) talking to the parent process on
# the other end of this pipe and not the filesystem
# or the original sys.stderr, so there's no point
# in trying to match the encoding of one of those
# objects.
stderr = io.TextIOWrapper(stderr, encoding="utf-8")
stderr.write(msg)
traceback.print_exc(file=stderr)
stderr.flush()
for fd in range(3):
os.close(fd)
except:
# Handle all errors during the error-reporting process
# silently to ensure that the child terminates.
pass
# See comment above about making sure that we reach this line
# of code.
os._exit(1)
# we are now in parent process
if collectorEnabled:
gc.enable()
self.status = -1 # this records the exit status of the child
def _setupChild(self, *args, **kwargs):
"""
Setup the child process. Override in subclasses.
"""
raise NotImplementedError()
def _execChild(self, path, uid, gid, executable, args, environment):
"""
The exec() which is done in the forked child.
"""
if path:
os.chdir(path)
if uid is not None or gid is not None:
if uid is None:
uid = os.geteuid()
if gid is None:
gid = os.getegid()
# set the UID before I actually exec the process
os.setuid(0)
os.setgid(0)
switchUID(uid, gid)
os.execvpe(executable, args, environment)
def __repr__(self):
"""
String representation of a process.
"""
return "<%s pid=%s status=%s>" % (self.__class__.__name__,
self.pid, self.status)
class _FDDetector(object):
"""
This class contains the logic necessary to decide which of the available
system techniques should be used to detect the open file descriptors for
the current process. The chosen technique gets monkey-patched into the
_listOpenFDs method of this class so that the detection only needs to occur
once.
@ivar listdir: The implementation of listdir to use. This gets overwritten
by the test cases.
@ivar getpid: The implementation of getpid to use, returns the PID of the
running process.
@ivar openfile: The implementation of open() to use, by default the Python
builtin.
"""
# So that we can unit test this
listdir = os.listdir
getpid = os.getpid
openfile = open
def __init__(self):
self._implementations = [
self._procFDImplementation, self._devFDImplementation,
self._fallbackFDImplementation]
def _listOpenFDs(self):
"""
Return an iterable of file descriptors which I{may} be open in this
process.
This will try to return the fewest possible descriptors without missing
any.
"""
self._listOpenFDs = self._getImplementation()
return self._listOpenFDs()
def _getImplementation(self):
"""
Pick a method which gives correct results for C{_listOpenFDs} in this
runtime environment.
This involves a lot of very platform-specific checks, some of which may
be relatively expensive. Therefore the returned method should be saved
and re-used, rather than always calling this method to determine what it
is.
See the implementation for the details of how a method is selected.
"""
for impl in self._implementations:
try:
before = impl()
except:
continue
with self.openfile("/dev/null", "r"):
after = impl()
if before != after:
return impl
# If no implementation can detect the newly opened file above, then just
# return the last one. The last one should therefore always be one
# which makes a simple static guess which includes all possible open
# file descriptors, but perhaps also many other values which do not
# correspond to file descriptors. For example, the scheme implemented
# by _fallbackFDImplementation is suitable to be the last entry.
return impl
def _devFDImplementation(self):
"""
Simple implementation for systems where /dev/fd actually works.
See: http://www.freebsd.org/cgi/man.cgi?fdescfs
"""
dname = "/dev/fd"
result = [int(fd) for fd in self.listdir(dname)]
return result
def _procFDImplementation(self):
"""
Simple implementation for systems where /proc/pid/fd exists (we assume
it works).
"""
dname = "/proc/%d/fd" % (self.getpid(),)
return [int(fd) for fd in self.listdir(dname)]
def _fallbackFDImplementation(self):
"""
Fallback implementation where either the resource module can inform us
about the upper bound of how many FDs to expect, or where we just guess
a constant maximum if there is no resource module.
All possible file descriptors from 0 to that upper bound are returned
with no attempt to exclude invalid file descriptor values.
"""
try:
import resource
except ImportError:
maxfds = 1024
else:
# OS-X reports 9223372036854775808. That's a lot of fds to close.
# OS-X should get the /dev/fd implementation instead, so mostly
# this check probably isn't necessary.
maxfds = min(1024, resource.getrlimit(resource.RLIMIT_NOFILE)[1])
return range(maxfds)
detector = _FDDetector()
def _listOpenFDs():
"""
Use the global detector object to figure out which FD implementation to
use.
"""
return detector._listOpenFDs()
@implementer(IProcessTransport)
class Process(_BaseProcess):
"""
An operating-system Process.
This represents an operating-system process with arbitrary input/output
pipes connected to it. Those pipes may represent standard input,
standard output, and standard error, or any other file descriptor.
On UNIX, this is implemented using fork(), exec(), pipe()
and fcntl(). These calls may not exist elsewhere so this
code is not cross-platform. (also, windows can only select
on sockets...)
"""
debug = False
debug_child = False
status = -1
pid = None
processWriterFactory = ProcessWriter
processReaderFactory = ProcessReader
def __init__(self,
reactor, executable, args, environment, path, proto,
uid=None, gid=None, childFDs=None):
"""
Spawn an operating-system process.
This is where the hard work of disconnecting all currently open
files / forking / executing the new process happens. (This is
executed automatically when a Process is instantiated.)
This will also run the subprocess as a given user ID and group ID, if
specified. (Implementation Note: this doesn't support all the arcane
nuances of setXXuid on UNIX: it will assume that either your effective
or real UID is 0.)
"""
if not proto:
assert 'r' not in childFDs.values()
assert 'w' not in childFDs.values()
_BaseProcess.__init__(self, proto)
self.pipes = {}
# keys are childFDs, we can sense them closing
# values are ProcessReader/ProcessWriters
helpers = {}
# keys are childFDs
# values are parentFDs
if childFDs is None:
childFDs = {0: "w", # we write to the child's stdin
1: "r", # we read from their stdout
2: "r", # and we read from their stderr
}
debug = self.debug
if debug: print("childFDs", childFDs)
_openedPipes = []
def pipe():
r, w = os.pipe()
_openedPipes.extend([r, w])
return r, w
# fdmap.keys() are filenos of pipes that are used by the child.
fdmap = {} # maps childFD to parentFD
try:
for childFD, target in items(childFDs):
if debug: print("[%d]" % childFD, target)
if target == "r":
# we need a pipe that the parent can read from
readFD, writeFD = pipe()
if debug: print("readFD=%d, writeFD=%d" % (readFD, writeFD))
fdmap[childFD] = writeFD # child writes to this
helpers[childFD] = readFD # parent reads from this
elif target == "w":
# we need a pipe that the parent can write to
readFD, writeFD = pipe()
if debug: print("readFD=%d, writeFD=%d" % (readFD, writeFD))
fdmap[childFD] = readFD # child reads from this
helpers[childFD] = writeFD # parent writes to this
else:
assert type(target) == int, '%r should be an int' % (target,)
fdmap[childFD] = target # parent ignores this
if debug: print("fdmap", fdmap)
if debug: print("helpers", helpers)
# the child only cares about fdmap.values()
self._fork(path, uid, gid, executable, args, environment, fdmap=fdmap)
except:
for pipe in _openedPipes:
os.close(pipe)
raise
# we are the parent process:
self.proto = proto
# arrange for the parent-side pipes to be read and written
for childFD, parentFD in items(helpers):
os.close(fdmap[childFD])
if childFDs[childFD] == "r":
reader = self.processReaderFactory(reactor, self, childFD,
parentFD)
self.pipes[childFD] = reader
if childFDs[childFD] == "w":
writer = self.processWriterFactory(reactor, self, childFD,
parentFD, forceReadHack=True)
self.pipes[childFD] = writer
try:
# the 'transport' is used for some compatibility methods
if self.proto is not None:
self.proto.makeConnection(self)
except:
log.err()
# The reactor might not be running yet. This might call back into
# processEnded synchronously, triggering an application-visible
# callback. That's probably not ideal. The replacement API for
# spawnProcess should improve upon this situation.
registerReapProcessHandler(self.pid, self)
def _setupChild(self, fdmap):
"""
fdmap[childFD] = parentFD
The child wants to end up with 'childFD' attached to what used to be
the parent's parentFD. As an example, a bash command run like
'command 2>&1' would correspond to an fdmap of {0:0, 1:1, 2:1}.
'command >foo.txt' would be {0:0, 1:os.open('foo.txt'), 2:2}.
This is accomplished in two steps::
1. close all file descriptors that aren't values of fdmap. This
means 0 .. maxfds (or just the open fds within that range, if
the platform supports '/proc/<pid>/fd').
2. for each childFD::
- if fdmap[childFD] == childFD, the descriptor is already in
place. Make sure the CLOEXEC flag is not set, then delete
the entry from fdmap.
- if childFD is in fdmap.values(), then the target descriptor
is busy. Use os.dup() to move it elsewhere, update all
fdmap[childFD] items that point to it, then close the
original. Then fall through to the next case.
- now fdmap[childFD] is not in fdmap.values(), and is free.
Use os.dup2() to move it to the right place, then close the
original.
"""
debug = self.debug_child
if debug:
errfd = sys.stderr
errfd.write("starting _setupChild\n")
destList = fdmap.values()
for fd in _listOpenFDs():
if fd in destList:
continue
if debug and fd == errfd.fileno():
continue
try:
os.close(fd)
except:
pass
# at this point, the only fds still open are the ones that need to
# be moved to their appropriate positions in the child (the targets
# of fdmap, i.e. fdmap.values() )
if debug: print("fdmap", fdmap, file=errfd)
for child in sorted(fdmap.keys()):
target = fdmap[child]
if target == child:
# fd is already in place
if debug: print("%d already in place" % target, file=errfd)
fdesc._unsetCloseOnExec(child)
else:
if child in fdmap.values():
# we can't replace child-fd yet, as some other mapping
# still needs the fd it wants to target. We must preserve
# that old fd by duping it to a new home.
newtarget = os.dup(child) # give it a safe home
if debug: print("os.dup(%d) -> %d" % (child, newtarget),
file=errfd)
os.close(child) # close the original
for c, p in items(fdmap):
if p == child:
fdmap[c] = newtarget # update all pointers
# now it should be available
if debug: print("os.dup2(%d,%d)" % (target, child), file=errfd)
os.dup2(target, child)
# At this point, the child has everything it needs. We want to close
# everything that isn't going to be used by the child, i.e.
# everything not in fdmap.keys(). The only remaining fds open are
# those in fdmap.values().
# Any given fd may appear in fdmap.values() multiple times, so we
# need to remove duplicates first.
old = []
for fd in fdmap.values():
if not fd in old:
if not fd in fdmap.keys():
old.append(fd)
if debug: print("old", old, file=errfd)
for fd in old:
os.close(fd)
self._resetSignalDisposition()
def writeToChild(self, childFD, data):
self.pipes[childFD].write(data)
def closeChildFD(self, childFD):
# for writer pipes, loseConnection tries to write the remaining data
# out to the pipe before closing it
# if childFD is not in the list of pipes, assume that it is already
# closed
if childFD in self.pipes:
self.pipes[childFD].loseConnection()
def pauseProducing(self):
for p in self.pipes.itervalues():
if isinstance(p, ProcessReader):
p.stopReading()
def resumeProducing(self):
for p in self.pipes.itervalues():
if isinstance(p, ProcessReader):
p.startReading()
# compatibility
def closeStdin(self):
"""
Call this to close standard input on this process.
"""
self.closeChildFD(0)
def closeStdout(self):
self.closeChildFD(1)
def closeStderr(self):
self.closeChildFD(2)
def loseConnection(self):
self.closeStdin()
self.closeStderr()
self.closeStdout()
def write(self, data):
"""
Call this to write to standard input on this process.
NOTE: This will silently lose data if there is no standard input.
"""
if 0 in self.pipes:
self.pipes[0].write(data)
def registerProducer(self, producer, streaming):
"""
Call this to register producer for standard input.
If there is no standard input producer.stopProducing() will
be called immediately.
"""
if 0 in self.pipes:
self.pipes[0].registerProducer(producer, streaming)
else:
producer.stopProducing()
def unregisterProducer(self):
"""
Call this to unregister producer for standard input."""
if 0 in self.pipes:
self.pipes[0].unregisterProducer()
def writeSequence(self, seq):
"""
Call this to write to standard input on this process.
NOTE: This will silently lose data if there is no standard input.
"""
if 0 in self.pipes:
self.pipes[0].writeSequence(seq)
def childDataReceived(self, name, data):
self.proto.childDataReceived(name, data)
def childConnectionLost(self, childFD, reason):
# this is called when one of the helpers (ProcessReader or
# ProcessWriter) notices their pipe has been closed
os.close(self.pipes[childFD].fileno())
del self.pipes[childFD]
try:
self.proto.childConnectionLost(childFD)
except:
log.err()
self.maybeCallProcessEnded()
def maybeCallProcessEnded(self):
# we don't call ProcessProtocol.processEnded until:
# the child has terminated, AND
# all writers have indicated an error status, AND
# all readers have indicated EOF
# This insures that we've gathered all output from the process.
if self.pipes:
return
if not self.lostProcess:
self.reapProcess()
return
_BaseProcess.maybeCallProcessEnded(self)
@implementer(IProcessTransport)
class PTYProcess(abstract.FileDescriptor, _BaseProcess):
"""
An operating-system Process that uses PTY support.
"""
status = -1
pid = None
def __init__(self, reactor, executable, args, environment, path, proto,
uid=None, gid=None, usePTY=None):
"""
Spawn an operating-system process.
This is where the hard work of disconnecting all currently open
files / forking / executing the new process happens. (This is
executed automatically when a Process is instantiated.)
This will also run the subprocess as a given user ID and group ID, if
specified. (Implementation Note: this doesn't support all the arcane
nuances of setXXuid on UNIX: it will assume that either your effective
or real UID is 0.)
"""
if pty is None and not isinstance(usePTY, (tuple, list)):
# no pty module and we didn't get a pty to use
raise NotImplementedError(
"cannot use PTYProcess on platforms without the pty module.")
abstract.FileDescriptor.__init__(self, reactor)
_BaseProcess.__init__(self, proto)
if isinstance(usePTY, (tuple, list)):
masterfd, slavefd, _ = usePTY
else:
masterfd, slavefd = pty.openpty()
try:
self._fork(path, uid, gid, executable, args, environment,
masterfd=masterfd, slavefd=slavefd)
except:
if not isinstance(usePTY, (tuple, list)):
os.close(masterfd)
os.close(slavefd)
raise
# we are now in parent process:
os.close(slavefd)
fdesc.setNonBlocking(masterfd)
self.fd = masterfd
self.startReading()
self.connected = 1
self.status = -1
try:
self.proto.makeConnection(self)
except:
log.err()
registerReapProcessHandler(self.pid, self)
def _setupChild(self, masterfd, slavefd):
"""
Set up child process after C{fork()} but before C{exec()}.
This involves:
- closing C{masterfd}, since it is not used in the subprocess
- creating a new session with C{os.setsid}
- changing the controlling terminal of the process (and the new
session) to point at C{slavefd}
- duplicating C{slavefd} to standard input, output, and error
- closing all other open file descriptors (according to
L{_listOpenFDs})
- re-setting all signal handlers to C{SIG_DFL}
@param masterfd: The master end of a PTY file descriptors opened with
C{openpty}.
@type masterfd: L{int}
@param slavefd: The slave end of a PTY opened with C{openpty}.
@type slavefd: L{int}
"""
os.close(masterfd)
os.setsid()
fcntl.ioctl(slavefd, termios.TIOCSCTTY, '')
for fd in range(3):
if fd != slavefd:
os.close(fd)
os.dup2(slavefd, 0) # stdin
os.dup2(slavefd, 1) # stdout
os.dup2(slavefd, 2) # stderr
for fd in _listOpenFDs():
if fd > 2:
try:
os.close(fd)
except:
pass
self._resetSignalDisposition()
def closeStdin(self):
# PTYs do not have stdin/stdout/stderr. They only have in and out, just
# like sockets. You cannot close one without closing off the entire PTY
pass
def closeStdout(self):
pass
def closeStderr(self):
pass
def doRead(self):
"""
Called when my standard output stream is ready for reading.
"""
return fdesc.readFromFD(
self.fd,
lambda data: self.proto.childDataReceived(1, data))
def fileno(self):
"""
This returns the file number of standard output on this process.
"""
return self.fd
def maybeCallProcessEnded(self):
# two things must happen before we call the ProcessProtocol's
# processEnded method. 1: the child process must die and be reaped
# (which calls our own processEnded method). 2: the child must close
# their stdin/stdout/stderr fds, causing the pty to close, causing
# our connectionLost method to be called. #2 can also be triggered
# by calling .loseConnection().
if self.lostProcess == 2:
_BaseProcess.maybeCallProcessEnded(self)
def connectionLost(self, reason):
"""
I call this to clean up when one or all of my connections has died.
"""
abstract.FileDescriptor.connectionLost(self, reason)
os.close(self.fd)
self.lostProcess += 1
self.maybeCallProcessEnded()
def writeSomeData(self, data):
"""
Write some data to the open process.
"""
return fdesc.writeToFD(self.fd, data)
|