1 # Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
3 # SPDX-License-Identifier: GPL-2.0
5 # Logic to spawn a sub-process and interact with its stdio.
14 class Timeout(Exception):
15 """An exception sub-class that indicates that a timeout occurred."""
19 """Represents the stdio of a freshly created sub-process. Commands may be
20 sent to the process, and responses waited for.
23 def __init__(self, args, cwd=None):
24 """Spawn (fork/exec) the sub-process.
27 args: array of processs arguments. argv[0] is the command to
29 cwd: the directory to run the process in, or None for no change.
37 self.logfile_read = None
42 (self.pid, self.fd) = pty.fork()
45 # For some reason, SIGHUP is set to SIG_IGN at this point when
46 # run under "go" (www.go.cd). Perhaps this happens under any
47 # background (non-interactive) system?
48 signal.signal(signal.SIGHUP, signal.SIG_DFL)
51 os.execvp(args[0], args)
53 print 'CHILD EXECEPTION:'
59 self.poll = select.poll()
60 self.poll.register(self.fd, select.POLLIN | select.POLLPRI | select.POLLERR | select.POLLHUP | select.POLLNVAL)
63 """Send unix signal "sig" to the child process.
66 sig: The signal number to send.
72 os.kill(self.pid, sig)
75 """Determine whether the child process is still running.
81 Boolean indicating whether process is alive.
87 w = os.waitpid(self.pid, os.WNOHANG)
95 """Send data to the sub-process's stdin.
98 data: The data to send to the process.
104 os.write(self.fd, data)
106 def expect(self, patterns):
107 """Wait for the sub-process to emit specific data.
109 This function waits for the process to emit one pattern from the
110 supplied list of patterns, or for a timeout to occur.
113 patterns: A list of strings or regex objects that we expect to
114 see in the sub-process' stdout.
117 The index within the patterns array of the pattern the process
121 Timeout, if the process did not emit any of the patterns within
125 for pi in xrange(len(patterns)):
126 if type(patterns[pi]) == type(''):
127 patterns[pi] = re.compile(patterns[pi])
129 tstart_s = time.time()
134 for pi in xrange(len(patterns)):
135 pattern = patterns[pi]
136 m = pattern.search(self.buf)
139 if earliest_m and m.start() >= earliest_m.start():
144 pos = earliest_m.start()
145 posafter = earliest_m.end() + 1
146 self.before = self.buf[:pos]
147 self.after = self.buf[pos:posafter]
148 self.buf = self.buf[posafter:]
151 tdelta_ms = (tnow_s - tstart_s) * 1000
152 if tdelta_ms > self.timeout:
154 events = self.poll.poll(self.timeout - tdelta_ms)
157 c = os.read(self.fd, 1024)
160 if self.logfile_read:
161 self.logfile_read.write(c)
164 if self.logfile_read:
165 self.logfile_read.flush()
168 """Close the stdio connection to the sub-process.
170 This also waits a reasonable time for the sub-process to stop running.
180 for i in xrange(100):
181 if not self.isalive():