1import codecs
2import errno
3import fcntl
4import io
5import os
6import pty
7import resource
8import signal
9import struct
10import sys
11import termios
12import time
13
14try:
15    import builtins  # Python 3
16except ImportError:
17    import __builtin__ as builtins  # Python 2
18
19# Constants
20from pty import (STDIN_FILENO, CHILD)
21
22from .util import which, PtyProcessError
23
24_platform = sys.platform.lower()
25
26# Solaris uses internal __fork_pty(). All others use pty.fork().
27_is_solaris = (
28    _platform.startswith('solaris') or
29    _platform.startswith('sunos'))
30
31if _is_solaris:
32    use_native_pty_fork = False
33    from . import _fork_pty
34else:
35    use_native_pty_fork = True
36
37PY3 = sys.version_info[0] >= 3
38
39if PY3:
40    def _byte(i):
41        return bytes([i])
42else:
43    def _byte(i):
44        return chr(i)
45
46    class FileNotFoundError(OSError): pass
47    class TimeoutError(OSError): pass
48
49_EOF, _INTR = None, None
50
51def _make_eof_intr():
52    """Set constants _EOF and _INTR.
53
54    This avoids doing potentially costly operations on module load.
55    """
56    global _EOF, _INTR
57    if (_EOF is not None) and (_INTR is not None):
58        return
59
60    # inherit EOF and INTR definitions from controlling process.
61    try:
62        from termios import VEOF, VINTR
63        fd = None
64        for name in 'stdin', 'stdout':
65            stream = getattr(sys, '__%s__' % name, None)
66            if stream is None or not hasattr(stream, 'fileno'):
67                continue
68            try:
69                fd = stream.fileno()
70            except ValueError:
71                continue
72        if fd is None:
73            # no fd, raise ValueError to fallback on CEOF, CINTR
74            raise ValueError("No stream has a fileno")
75        intr = ord(termios.tcgetattr(fd)[6][VINTR])
76        eof = ord(termios.tcgetattr(fd)[6][VEOF])
77    except (ImportError, OSError, IOError, ValueError, termios.error):
78        # unless the controlling process is also not a terminal,
79        # such as cron(1), or when stdin and stdout are both closed.
80        # Fall-back to using CEOF and CINTR. There
81        try:
82            from termios import CEOF, CINTR
83            (intr, eof) = (CINTR, CEOF)
84        except ImportError:
85            #                         ^C, ^D
86            (intr, eof) = (3, 4)
87
88    _INTR = _byte(intr)
89    _EOF = _byte(eof)
90
91# setecho and setwinsize are pulled out here because on some platforms, we need
92# to do this from the child before we exec()
93
94def _setecho(fd, state):
95    errmsg = 'setecho() may not be called on this platform (it may still be possible to enable/disable echo when spawning the child process)'
96
97    try:
98        attr = termios.tcgetattr(fd)
99    except termios.error as err:
100        if err.args[0] == errno.EINVAL:
101            raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
102        raise
103
104    if state:
105        attr[3] = attr[3] | termios.ECHO
106    else:
107        attr[3] = attr[3] & ~termios.ECHO
108
109    try:
110        # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent and
111        # blocked on some platforms. TCSADRAIN would probably be ideal.
112        termios.tcsetattr(fd, termios.TCSANOW, attr)
113    except IOError as err:
114        if err.args[0] == errno.EINVAL:
115            raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
116        raise
117
118def _setwinsize(fd, rows, cols):
119    # Some very old platforms have a bug that causes the value for
120    # termios.TIOCSWINSZ to be truncated. There was a hack here to work
121    # around this, but it caused problems with newer platforms so has been
122    # removed. For details see https://github.com/pexpect/pexpect/issues/39
123    TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
124    # Note, assume ws_xpixel and ws_ypixel are zero.
125    s = struct.pack('HHHH', rows, cols, 0, 0)
126    fcntl.ioctl(fd, TIOCSWINSZ, s)
127
128class PtyProcess(object):
129    '''This class represents a process running in a pseudoterminal.
130
131    The main constructor is the :meth:`spawn` classmethod.
132    '''
133    string_type = bytes
134    if PY3:
135        linesep = os.linesep.encode('ascii')
136        crlf = '\r\n'.encode('ascii')
137
138        @staticmethod
139        def write_to_stdout(b):
140            try:
141                return sys.stdout.buffer.write(b)
142            except AttributeError:
143                # If stdout has been replaced, it may not have .buffer
144                return sys.stdout.write(b.decode('ascii', 'replace'))
145    else:
146        linesep = os.linesep
147        crlf = '\r\n'
148        write_to_stdout = sys.stdout.write
149
150    encoding = None
151
152    argv = None
153    env = None
154    launch_dir = None
155
156    def __init__(self, pid, fd):
157        _make_eof_intr()  # Ensure _EOF and _INTR are calculated
158        self.pid = pid
159        self.fd = fd
160        readf = io.open(fd, 'rb', buffering=0)
161        writef = io.open(fd, 'wb', buffering=0, closefd=False)
162        self.fileobj = io.BufferedRWPair(readf, writef)
163
164        self.terminated = False
165        self.closed = False
166        self.exitstatus = None
167        self.signalstatus = None
168        # status returned by os.waitpid
169        self.status = None
170        self.flag_eof = False
171        # Used by close() to give kernel time to update process status.
172        # Time in seconds.
173        self.delayafterclose = 0.1
174        # Used by terminate() to give kernel time to update process status.
175        # Time in seconds.
176        self.delayafterterminate = 0.1
177
178    @classmethod
179    def spawn(
180            cls, argv, cwd=None, env=None, echo=True, preexec_fn=None,
181            dimensions=(24, 80)):
182        '''Start the given command in a child process in a pseudo terminal.
183
184        This does all the fork/exec type of stuff for a pty, and returns an
185        instance of PtyProcess.
186
187        If preexec_fn is supplied, it will be called with no arguments in the
188        child process before exec-ing the specified command.
189        It may, for instance, set signal handlers to SIG_DFL or SIG_IGN.
190
191        Dimensions of the psuedoterminal used for the subprocess can be
192        specified as a tuple (rows, cols), or the default (24, 80) will be used.
193        '''
194        # Note that it is difficult for this method to fail.
195        # You cannot detect if the child process cannot start.
196        # So the only way you can tell if the child process started
197        # or not is to try to read from the file descriptor. If you get
198        # EOF immediately then it means that the child is already dead.
199        # That may not necessarily be bad because you may have spawned a child
200        # that performs some task; creates no stdout output; and then dies.
201
202        if not isinstance(argv, (list, tuple)):
203            raise TypeError("Expected a list or tuple for argv, got %r" % argv)
204
205        # Shallow copy of argv so we can modify it
206        argv = argv[:]
207        command = argv[0]
208
209        command_with_path = which(command)
210        if command_with_path is None:
211            raise FileNotFoundError('The command was not found or was not ' +
212                                    'executable: %s.' % command)
213        command = command_with_path
214        argv[0] = command
215
216        # [issue #119] To prevent the case where exec fails and the user is
217        # stuck interacting with a python child process instead of whatever
218        # was expected, we implement the solution from
219        # http://stackoverflow.com/a/3703179 to pass the exception to the
220        # parent process
221
222        # [issue #119] 1. Before forking, open a pipe in the parent process.
223        exec_err_pipe_read, exec_err_pipe_write = os.pipe()
224
225        if use_native_pty_fork:
226            pid, fd = pty.fork()
227        else:
228            # Use internal fork_pty, for Solaris
229            pid, fd = _fork_pty.fork_pty()
230
231        # Some platforms must call setwinsize() and setecho() from the
232        # child process, and others from the primary process. We do both,
233        # allowing IOError for either.
234
235        if pid == CHILD:
236            # set window size
237            try:
238                _setwinsize(STDIN_FILENO, *dimensions)
239            except IOError as err:
240                if err.args[0] not in (errno.EINVAL, errno.ENOTTY):
241                    raise
242
243            # disable echo if spawn argument echo was unset
244            if not echo:
245                try:
246                    _setecho(STDIN_FILENO, False)
247                except (IOError, termios.error) as err:
248                    if err.args[0] not in (errno.EINVAL, errno.ENOTTY):
249                        raise
250
251            # [issue #119] 3. The child closes the reading end and sets the
252            # close-on-exec flag for the writing end.
253            os.close(exec_err_pipe_read)
254            fcntl.fcntl(exec_err_pipe_write, fcntl.F_SETFD, fcntl.FD_CLOEXEC)
255
256            # Do not allow child to inherit open file descriptors from parent,
257            # with the exception of the exec_err_pipe_write of the pipe
258            # Impose ceiling on max_fd: AIX bugfix for users with unlimited
259            # nofiles where resource.RLIMIT_NOFILE is 2^63-1 and os.closerange()
260            # occasionally raises out of range error
261            max_fd = min(1048576, resource.getrlimit(resource.RLIMIT_NOFILE)[0])
262            os.closerange(3, exec_err_pipe_write)
263            os.closerange(exec_err_pipe_write+1, max_fd)
264
265            if cwd is not None:
266                os.chdir(cwd)
267
268            if preexec_fn is not None:
269                try:
270                    preexec_fn()
271                except Exception as e:
272                    ename = type(e).__name__
273                    tosend = '{}:0:{}'.format(ename, str(e))
274                    if PY3:
275                        tosend = tosend.encode('utf-8')
276
277                    os.write(exec_err_pipe_write, tosend)
278                    os.close(exec_err_pipe_write)
279                    os._exit(1)
280
281            try:
282                if env is None:
283                    os.execv(command, argv)
284                else:
285                    os.execvpe(command, argv, env)
286            except OSError as err:
287                # [issue #119] 5. If exec fails, the child writes the error
288                # code back to the parent using the pipe, then exits.
289                tosend = 'OSError:{}:{}'.format(err.errno, str(err))
290                if PY3:
291                    tosend = tosend.encode('utf-8')
292                os.write(exec_err_pipe_write, tosend)
293                os.close(exec_err_pipe_write)
294                os._exit(os.EX_OSERR)
295
296        # Parent
297        inst = cls(pid, fd)
298
299        # Set some informational attributes
300        inst.argv = argv
301        if env is not None:
302            inst.env = env
303        if cwd is not None:
304            inst.launch_dir = cwd
305
306        # [issue #119] 2. After forking, the parent closes the writing end
307        # of the pipe and reads from the reading end.
308        os.close(exec_err_pipe_write)
309        exec_err_data = os.read(exec_err_pipe_read, 4096)
310        os.close(exec_err_pipe_read)
311
312        # [issue #119] 6. The parent reads eof (a zero-length read) if the
313        # child successfully performed exec, since close-on-exec made
314        # successful exec close the writing end of the pipe. Or, if exec
315        # failed, the parent reads the error code and can proceed
316        # accordingly. Either way, the parent blocks until the child calls
317        # exec.
318        if len(exec_err_data) != 0:
319            try:
320                errclass, errno_s, errmsg = exec_err_data.split(b':', 2)
321                exctype = getattr(builtins, errclass.decode('ascii'), Exception)
322
323                exception = exctype(errmsg.decode('utf-8', 'replace'))
324                if exctype is OSError:
325                    exception.errno = int(errno_s)
326            except:
327                raise Exception('Subprocess failed, got bad error data: %r'
328                                    % exec_err_data)
329            else:
330                raise exception
331
332        try:
333            inst.setwinsize(*dimensions)
334        except IOError as err:
335            if err.args[0] not in (errno.EINVAL, errno.ENOTTY, errno.ENXIO):
336                raise
337
338        return inst
339
340    def __repr__(self):
341        clsname = type(self).__name__
342        if self.argv is not None:
343            args = [repr(self.argv)]
344            if self.env is not None:
345                args.append("env=%r" % self.env)
346            if self.launch_dir is not None:
347                args.append("cwd=%r" % self.launch_dir)
348
349            return "{}.spawn({})".format(clsname, ", ".join(args))
350
351        else:
352            return "{}(pid={}, fd={})".format(clsname, self.pid, self.fd)
353
354    @staticmethod
355    def _coerce_send_string(s):
356        if not isinstance(s, bytes):
357            return s.encode('utf-8')
358        return s
359
360    @staticmethod
361    def _coerce_read_string(s):
362        return s
363
364    def __del__(self):
365        '''This makes sure that no system resources are left open. Python only
366        garbage collects Python objects. OS file descriptors are not Python
367        objects, so they must be handled explicitly. If the child file
368        descriptor was opened outside of this class (passed to the constructor)
369        then this does not close it. '''
370
371        if not self.closed:
372            # It is possible for __del__ methods to execute during the
373            # teardown of the Python VM itself. Thus self.close() may
374            # trigger an exception because os.close may be None.
375            try:
376                self.close()
377            # which exception, shouldn't we catch explicitly .. ?
378            except:
379                pass
380
381
382    def fileno(self):
383        '''This returns the file descriptor of the pty for the child.
384        '''
385        return self.fd
386
387    def close(self, force=True):
388        '''This closes the connection with the child application. Note that
389        calling close() more than once is valid. This emulates standard Python
390        behavior with files. Set force to True if you want to make sure that
391        the child is terminated (SIGKILL is sent if the child ignores SIGHUP
392        and SIGINT). '''
393        if not self.closed:
394            self.flush()
395            self.fileobj.close() # Closes the file descriptor
396            # Give kernel time to update process status.
397            time.sleep(self.delayafterclose)
398            if self.isalive():
399                if not self.terminate(force):
400                    raise PtyProcessError('Could not terminate the child.')
401            self.fd = -1
402            self.closed = True
403            #self.pid = None
404
405    def flush(self):
406        '''This does nothing. It is here to support the interface for a
407        File-like object. '''
408
409        pass
410
411    def isatty(self):
412        '''This returns True if the file descriptor is open and connected to a
413        tty(-like) device, else False.
414
415        On SVR4-style platforms implementing streams, such as SunOS and HP-UX,
416        the child pty may not appear as a terminal device.  This means
417        methods such as setecho(), setwinsize(), getwinsize() may raise an
418        IOError. '''
419
420        return os.isatty(self.fd)
421
422    def waitnoecho(self, timeout=None):
423        '''This waits until the terminal ECHO flag is set False. This returns
424        True if the echo mode is off. This returns False if the ECHO flag was
425        not set False before the timeout. This can be used to detect when the
426        child is waiting for a password. Usually a child application will turn
427        off echo mode when it is waiting for the user to enter a password. For
428        example, instead of expecting the "password:" prompt you can wait for
429        the child to set ECHO off::
430
431            p = pexpect.spawn('ssh user@example.com')
432            p.waitnoecho()
433            p.sendline(mypassword)
434
435        If timeout==None then this method to block until ECHO flag is False.
436        '''
437
438        if timeout is not None:
439            end_time = time.time() + timeout
440        while True:
441            if not self.getecho():
442                return True
443            if timeout < 0 and timeout is not None:
444                return False
445            if timeout is not None:
446                timeout = end_time - time.time()
447            time.sleep(0.1)
448
449    def getecho(self):
450        '''This returns the terminal echo mode. This returns True if echo is
451        on or False if echo is off. Child applications that are expecting you
452        to enter a password often set ECHO False. See waitnoecho().
453
454        Not supported on platforms where ``isatty()`` returns False.  '''
455
456        try:
457            attr = termios.tcgetattr(self.fd)
458        except termios.error as err:
459            errmsg = 'getecho() may not be called on this platform'
460            if err.args[0] == errno.EINVAL:
461                raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
462            raise
463
464        self.echo = bool(attr[3] & termios.ECHO)
465        return self.echo
466
467    def setecho(self, state):
468        '''This sets the terminal echo mode on or off. Note that anything the
469        child sent before the echo will be lost, so you should be sure that
470        your input buffer is empty before you call setecho(). For example, the
471        following will work as expected::
472
473            p = pexpect.spawn('cat') # Echo is on by default.
474            p.sendline('1234') # We expect see this twice from the child...
475            p.expect(['1234']) # ... once from the tty echo...
476            p.expect(['1234']) # ... and again from cat itself.
477            p.setecho(False) # Turn off tty echo
478            p.sendline('abcd') # We will set this only once (echoed by cat).
479            p.sendline('wxyz') # We will set this only once (echoed by cat)
480            p.expect(['abcd'])
481            p.expect(['wxyz'])
482
483        The following WILL NOT WORK because the lines sent before the setecho
484        will be lost::
485
486            p = pexpect.spawn('cat')
487            p.sendline('1234')
488            p.setecho(False) # Turn off tty echo
489            p.sendline('abcd') # We will set this only once (echoed by cat).
490            p.sendline('wxyz') # We will set this only once (echoed by cat)
491            p.expect(['1234'])
492            p.expect(['1234'])
493            p.expect(['abcd'])
494            p.expect(['wxyz'])
495
496
497        Not supported on platforms where ``isatty()`` returns False.
498        '''
499        _setecho(self.fd, state)
500
501        self.echo = state
502
503    def read(self, size=1024):
504        """Read and return at most ``size`` bytes from the pty.
505
506        Can block if there is nothing to read. Raises :exc:`EOFError` if the
507        terminal was closed.
508
509        Unlike Pexpect's ``read_nonblocking`` method, this doesn't try to deal
510        with the vagaries of EOF on platforms that do strange things, like IRIX
511        or older Solaris systems. It handles the errno=EIO pattern used on
512        Linux, and the empty-string return used on BSD platforms and (seemingly)
513        on recent Solaris.
514        """
515        try:
516            s = self.fileobj.read1(size)
517        except (OSError, IOError) as err:
518            if err.args[0] == errno.EIO:
519                # Linux-style EOF
520                self.flag_eof = True
521                raise EOFError('End Of File (EOF). Exception style platform.')
522            raise
523        if s == b'':
524            # BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
525            self.flag_eof = True
526            raise EOFError('End Of File (EOF). Empty string style platform.')
527
528        return s
529
530    def readline(self):
531        """Read one line from the pseudoterminal, and return it as unicode.
532
533        Can block if there is nothing to read. Raises :exc:`EOFError` if the
534        terminal was closed.
535        """
536        try:
537            s = self.fileobj.readline()
538        except (OSError, IOError) as err:
539            if err.args[0] == errno.EIO:
540                # Linux-style EOF
541                self.flag_eof = True
542                raise EOFError('End Of File (EOF). Exception style platform.')
543            raise
544        if s == b'':
545            # BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
546            self.flag_eof = True
547            raise EOFError('End Of File (EOF). Empty string style platform.')
548
549        return s
550
551    def _writeb(self, b, flush=True):
552        n = self.fileobj.write(b)
553        if flush:
554            self.fileobj.flush()
555        return n
556
557    def write(self, s, flush=True):
558        """Write bytes to the pseudoterminal.
559
560        Returns the number of bytes written.
561        """
562        return self._writeb(s, flush=flush)
563
564    def sendcontrol(self, char):
565        '''Helper method that wraps send() with mnemonic access for sending control
566        character to the child (such as Ctrl-C or Ctrl-D).  For example, to send
567        Ctrl-G (ASCII 7, bell, '\a')::
568
569            child.sendcontrol('g')
570
571        See also, sendintr() and sendeof().
572        '''
573        char = char.lower()
574        a = ord(char)
575        if 97 <= a <= 122:
576            a = a - ord('a') + 1
577            byte = _byte(a)
578            return self._writeb(byte), byte
579        d = {'@': 0, '`': 0,
580            '[': 27, '{': 27,
581            '\\': 28, '|': 28,
582            ']': 29, '}': 29,
583            '^': 30, '~': 30,
584            '_': 31,
585            '?': 127}
586        if char not in d:
587            return 0, b''
588
589        byte = _byte(d[char])
590        return self._writeb(byte), byte
591
592    def sendeof(self):
593        '''This sends an EOF to the child. This sends a character which causes
594        the pending parent output buffer to be sent to the waiting child
595        program without waiting for end-of-line. If it is the first character
596        of the line, the read() in the user program returns 0, which signifies
597        end-of-file. This means to work as expected a sendeof() has to be
598        called at the beginning of a line. This method does not send a newline.
599        It is the responsibility of the caller to ensure the eof is sent at the
600        beginning of a line. '''
601
602        return self._writeb(_EOF), _EOF
603
604    def sendintr(self):
605        '''This sends a SIGINT to the child. It does not require
606        the SIGINT to be the first character on a line. '''
607
608        return self._writeb(_INTR), _INTR
609
610    def eof(self):
611        '''This returns True if the EOF exception was ever raised.
612        '''
613
614        return self.flag_eof
615
616    def terminate(self, force=False):
617        '''This forces a child process to terminate. It starts nicely with
618        SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
619        returns True if the child was terminated. This returns False if the
620        child could not be terminated. '''
621
622        if not self.isalive():
623            return True
624        try:
625            self.kill(signal.SIGHUP)
626            time.sleep(self.delayafterterminate)
627            if not self.isalive():
628                return True
629            self.kill(signal.SIGCONT)
630            time.sleep(self.delayafterterminate)
631            if not self.isalive():
632                return True
633            self.kill(signal.SIGINT)
634            time.sleep(self.delayafterterminate)
635            if not self.isalive():
636                return True
637            if force:
638                self.kill(signal.SIGKILL)
639                time.sleep(self.delayafterterminate)
640                if not self.isalive():
641                    return True
642                else:
643                    return False
644            return False
645        except OSError:
646            # I think there are kernel timing issues that sometimes cause
647            # this to happen. I think isalive() reports True, but the
648            # process is dead to the kernel.
649            # Make one last attempt to see if the kernel is up to date.
650            time.sleep(self.delayafterterminate)
651            if not self.isalive():
652                return True
653            else:
654                return False
655
656    def wait(self):
657        '''This waits until the child exits. This is a blocking call. This will
658        not read any data from the child, so this will block forever if the
659        child has unread output and has terminated. In other words, the child
660        may have printed output then called exit(), but, the child is
661        technically still alive until its output is read by the parent. '''
662
663        if self.isalive():
664            pid, status = os.waitpid(self.pid, 0)
665        else:
666            return self.exitstatus
667        self.exitstatus = os.WEXITSTATUS(status)
668        if os.WIFEXITED(status):
669            self.status = status
670            self.exitstatus = os.WEXITSTATUS(status)
671            self.signalstatus = None
672            self.terminated = True
673        elif os.WIFSIGNALED(status):
674            self.status = status
675            self.exitstatus = None
676            self.signalstatus = os.WTERMSIG(status)
677            self.terminated = True
678        elif os.WIFSTOPPED(status):  # pragma: no cover
679            # You can't call wait() on a child process in the stopped state.
680            raise PtyProcessError('Called wait() on a stopped child ' +
681                    'process. This is not supported. Is some other ' +
682                    'process attempting job control with our child pid?')
683        return self.exitstatus
684
685    def isalive(self):
686        '''This tests if the child process is running or not. This is
687        non-blocking. If the child was terminated then this will read the
688        exitstatus or signalstatus of the child. This returns True if the child
689        process appears to be running or False if not. It can take literally
690        SECONDS for Solaris to return the right status. '''
691
692        if self.terminated:
693            return False
694
695        if self.flag_eof:
696            # This is for Linux, which requires the blocking form
697            # of waitpid to get the status of a defunct process.
698            # This is super-lame. The flag_eof would have been set
699            # in read_nonblocking(), so this should be safe.
700            waitpid_options = 0
701        else:
702            waitpid_options = os.WNOHANG
703
704        try:
705            pid, status = os.waitpid(self.pid, waitpid_options)
706        except OSError as e:
707            # No child processes
708            if e.errno == errno.ECHILD:
709                raise PtyProcessError('isalive() encountered condition ' +
710                        'where "terminated" is 0, but there was no child ' +
711                        'process. Did someone else call waitpid() ' +
712                        'on our process?')
713            else:
714                raise
715
716        # I have to do this twice for Solaris.
717        # I can't even believe that I figured this out...
718        # If waitpid() returns 0 it means that no child process
719        # wishes to report, and the value of status is undefined.
720        if pid == 0:
721            try:
722                ### os.WNOHANG) # Solaris!
723                pid, status = os.waitpid(self.pid, waitpid_options)
724            except OSError as e:  # pragma: no cover
725                # This should never happen...
726                if e.errno == errno.ECHILD:
727                    raise PtyProcessError('isalive() encountered condition ' +
728                            'that should never happen. There was no child ' +
729                            'process. Did someone else call waitpid() ' +
730                            'on our process?')
731                else:
732                    raise
733
734            # If pid is still 0 after two calls to waitpid() then the process
735            # really is alive. This seems to work on all platforms, except for
736            # Irix which seems to require a blocking call on waitpid or select,
737            # so I let read_nonblocking take care of this situation
738            # (unfortunately, this requires waiting through the timeout).
739            if pid == 0:
740                return True
741
742        if pid == 0:
743            return True
744
745        if os.WIFEXITED(status):
746            self.status = status
747            self.exitstatus = os.WEXITSTATUS(status)
748            self.signalstatus = None
749            self.terminated = True
750        elif os.WIFSIGNALED(status):
751            self.status = status
752            self.exitstatus = None
753            self.signalstatus = os.WTERMSIG(status)
754            self.terminated = True
755        elif os.WIFSTOPPED(status):
756            raise PtyProcessError('isalive() encountered condition ' +
757                    'where child process is stopped. This is not ' +
758                    'supported. Is some other process attempting ' +
759                    'job control with our child pid?')
760        return False
761
762    def kill(self, sig):
763        """Send the given signal to the child application.
764
765        In keeping with UNIX tradition it has a misleading name. It does not
766        necessarily kill the child unless you send the right signal. See the
767        :mod:`signal` module for constants representing signal numbers.
768        """
769
770        # Same as os.kill, but the pid is given for you.
771        if self.isalive():
772            os.kill(self.pid, sig)
773
774    def getwinsize(self):
775        """Return the window size of the pseudoterminal as a tuple (rows, cols).
776        """
777        TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912)
778        s = struct.pack('HHHH', 0, 0, 0, 0)
779        x = fcntl.ioctl(self.fd, TIOCGWINSZ, s)
780        return struct.unpack('HHHH', x)[0:2]
781
782    def setwinsize(self, rows, cols):
783        """Set the terminal window size of the child tty.
784
785        This will cause a SIGWINCH signal to be sent to the child. This does not
786        change the physical window size. It changes the size reported to
787        TTY-aware applications like vi or curses -- applications that respond to
788        the SIGWINCH signal.
789        """
790        return _setwinsize(self.fd, rows, cols)
791
792
793class PtyProcessUnicode(PtyProcess):
794    """Unicode wrapper around a process running in a pseudoterminal.
795
796    This class exposes a similar interface to :class:`PtyProcess`, but its read
797    methods return unicode, and its :meth:`write` accepts unicode.
798    """
799    if PY3:
800        string_type = str
801    else:
802        string_type = unicode   # analysis:ignore
803
804    def __init__(self, pid, fd, encoding='utf-8', codec_errors='strict'):
805        super(PtyProcessUnicode, self).__init__(pid, fd)
806        self.encoding = encoding
807        self.codec_errors = codec_errors
808        self.decoder = codecs.getincrementaldecoder(encoding)(errors=codec_errors)
809
810    def read(self, size=1024):
811        """Read at most ``size`` bytes from the pty, return them as unicode.
812
813        Can block if there is nothing to read. Raises :exc:`EOFError` if the
814        terminal was closed.
815
816        The size argument still refers to bytes, not unicode code points.
817        """
818        b = super(PtyProcessUnicode, self).read(size)
819        return self.decoder.decode(b, final=False)
820
821    def readline(self):
822        """Read one line from the pseudoterminal, and return it as unicode.
823
824        Can block if there is nothing to read. Raises :exc:`EOFError` if the
825        terminal was closed.
826        """
827        b = super(PtyProcessUnicode, self).readline()
828        return self.decoder.decode(b, final=False)
829
830    def write(self, s):
831        """Write the unicode string ``s`` to the pseudoterminal.
832
833        Returns the number of bytes written.
834        """
835        b = s.encode(self.encoding)
836        return super(PtyProcessUnicode, self).write(b)
837