This instance will be upgraded to Heptapod 0.27.1 on 2021-12-08 at 22:00 UTC+1 (a few minutes of down time)

procutil.py 23.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
# procutil.py - utility for managing processes and executable environment
#
#  Copyright 2005 K. Thananchayan <thananck@yahoo.com>
#  Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
#  Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.

from __future__ import absolute_import

12
import contextlib
13
import errno
14
15
16
17
18
import io
import os
import signal
import subprocess
import sys
19
import threading
20
21
22
import time

from ..i18n import _
23
24
25
26
from ..pycompat import (
    getattr,
    open,
)
27
28
29
30
31
32
33
34

from .. import (
    encoding,
    error,
    policy,
    pycompat,
)

35
36
37
# Import like this to keep import-checker happy
from ..utils import resourceutil

38
osutil = policy.importmod('osutil')
39

40
41
42
43
44
if pycompat.iswindows:
    from .. import windows as platform
else:
    from .. import posix as platform

45

46
47
48
49
50
51
def isatty(fp):
    try:
        return fp.isatty()
    except AttributeError:
        return False

52

53
54
55
class LineBufferedWrapper(object):
    def __init__(self, orig):
        self.orig = orig
56

57
58
    def __getattr__(self, attr):
        return getattr(self.orig, attr)
59

60
61
62
63
64
65
    def write(self, s):
        orig = self.orig
        res = orig.write(s)
        if s.endswith(b'\n'):
            orig.flush()
        return res
66
67


68
io.BufferedIOBase.register(LineBufferedWrapper)
69
70


71
72
73
74
75
76
77
78
79
80
81
82
def make_line_buffered(stream):
    if pycompat.ispy3 and not isinstance(stream, io.BufferedIOBase):
        # On Python 3, buffered streams can be expected to subclass
        # BufferedIOBase. This is definitively the case for the streams
        # initialized by the interpreter. For unbuffered streams, we don't need
        # to emulate line buffering.
        return stream
    if isinstance(stream, LineBufferedWrapper):
        return stream
    return LineBufferedWrapper(stream)


83
84
85
86
87
88
89
def unwrap_line_buffered(stream):
    if isinstance(stream, LineBufferedWrapper):
        assert not isinstance(stream.orig, LineBufferedWrapper)
        return stream.orig
    return stream


90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
class WriteAllWrapper(object):
    def __init__(self, orig):
        self.orig = orig

    def __getattr__(self, attr):
        return getattr(self.orig, attr)

    def write(self, s):
        write1 = self.orig.write
        m = memoryview(s)
        total_to_write = len(s)
        total_written = 0
        while total_written < total_to_write:
            total_written += write1(m[total_written:])
        return total_written


io.IOBase.register(WriteAllWrapper)


110
def _make_write_all(stream):
111
112
113
114
115
116
117
118
119
120
121
122
    assert pycompat.ispy3
    if isinstance(stream, WriteAllWrapper):
        return stream
    if isinstance(stream, io.BufferedIOBase):
        # The io.BufferedIOBase.write() contract guarantees that all data is
        # written.
        return stream
    # In general, the write() method of streams is free to write only part of
    # the data.
    return WriteAllWrapper(stream)


123
if pycompat.ispy3:
124
    # Python 3 implements its own I/O streams.
125
126
    # TODO: .buffer might not exist if std streams were replaced; we'll need
    # a silly wrapper to make a bytes stream backed by a unicode one.
127
128

    # sys.stdin can be None
129
130
131
132
133
    if sys.stdin:
        stdin = sys.stdin.buffer
    else:
        stdin = open(os.devnull, 'rb')
        os.close(stdin.fileno())
134
135
136
137
138
139
140
141
142
143
    if sys.stdout:
        stdout = _make_write_all(sys.stdout.buffer)
    else:
        stdout = open(os.devnull, 'rb')
        os.close(stdout.fileno())
    if sys.stderr:
        stderr = _make_write_all(sys.stderr.buffer)
    else:
        stderr = open(os.devnull, 'rb')
        os.close(stderr.fileno())
144
145
146
147
    if pycompat.iswindows:
        # Work around Windows bugs.
        stdout = platform.winstdout(stdout)
        stderr = platform.winstdout(stderr)
148
149
150
    if isatty(stdout):
        # The standard library doesn't offer line-buffered binary streams.
        stdout = make_line_buffered(stdout)
151
else:
152
    # Python 2 uses the I/O streams provided by the C library.
153
154
    stdin = sys.stdin
    stdout = sys.stdout
155
156
157
158
159
    stderr = sys.stderr
    if pycompat.iswindows:
        # Work around Windows bugs.
        stdout = platform.winstdout(stdout)
        stderr = platform.winstdout(stderr)
160
161
162
163
164
165
166
167
168
    if isatty(stdout):
        if pycompat.iswindows:
            # The Windows C runtime library doesn't support line buffering.
            stdout = make_line_buffered(stdout)
        else:
            # glibc determines buffering on first write to stdout - if we
            # replace a TTY destined stdout with a pipe destined stdout (e.g.
            # pager), we want line buffering.
            stdout = os.fdopen(stdout.fileno(), 'wb', 1)
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


findexe = platform.findexe
_gethgcmd = platform.gethgcmd
getuser = platform.getuser
getpid = os.getpid
hidewindow = platform.hidewindow
readpipe = platform.readpipe
setbinary = platform.setbinary
setsignalhandler = platform.setsignalhandler
shellquote = platform.shellquote
shellsplit = platform.shellsplit
spawndetached = platform.spawndetached
sshargs = platform.sshargs
testpid = platform.testpid

try:
    setprocname = osutil.setprocname
except AttributeError:
    pass
try:
    unblocksignal = osutil.unblocksignal
except AttributeError:
    pass

closefds = pycompat.isposix

196

197
def explainexit(code):
198
    """return a message describing a subprocess status
199
200
    (codes from kill are negative - not os.system/wait encoding)"""
    if code >= 0:
201
202
        return _(b"exited with status %d") % code
    return _(b"killed by signal %d") % -code
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
class _pfile(object):
    """File-like wrapper for a stream opened by subprocess.Popen()"""

    def __init__(self, proc, fp):
        self._proc = proc
        self._fp = fp

    def close(self):
        # unlike os.popen(), this returns an integer in subprocess coding
        self._fp.close()
        return self._proc.wait()

    def __iter__(self):
        return iter(self._fp)

    def __getattr__(self, attr):
        return getattr(self._fp, attr)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, exc_tb):
        self.close()

229

230
231
def popen(cmd, mode=b'rb', bufsize=-1):
    if mode == b'rb':
232
        return _popenreader(cmd, bufsize)
233
    elif mode == b'wb':
234
        return _popenwriter(cmd, bufsize)
235
    raise error.ProgrammingError(b'unsupported mode: %r' % mode)
236

237

238
def _popenreader(cmd, bufsize):
239
    p = subprocess.Popen(
240
        tonativestr(cmd),
241
242
243
244
245
        shell=True,
        bufsize=bufsize,
        close_fds=closefds,
        stdout=subprocess.PIPE,
    )
246
247
    return _pfile(p, p.stdout)

248

249
def _popenwriter(cmd, bufsize):
250
    p = subprocess.Popen(
251
        tonativestr(cmd),
252
253
254
255
256
        shell=True,
        bufsize=bufsize,
        close_fds=closefds,
        stdin=subprocess.PIPE,
    )
257
258
    return _pfile(p, p.stdin)

259

260
def popen2(cmd, env=None):
261
262
263
    # Setting bufsize to -1 lets the system decide the buffer size.
    # The default for bufsize is 0, meaning unbuffered. This leads to
    # poor performance on Mac OS X: http://bugs.python.org/issue4194
264
265
266
267
268
269
270
271
272
    p = subprocess.Popen(
        tonativestr(cmd),
        shell=True,
        bufsize=-1,
        close_fds=closefds,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        env=tonativeenv(env),
    )
273
274
    return p.stdin, p.stdout

275

276
277
def popen3(cmd, env=None):
    stdin, stdout, stderr, p = popen4(cmd, env)
278
279
    return stdin, stdout, stderr

280

281
def popen4(cmd, env=None, bufsize=-1):
282
283
284
285
286
287
288
289
290
291
    p = subprocess.Popen(
        tonativestr(cmd),
        shell=True,
        bufsize=bufsize,
        close_fds=closefds,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        env=tonativeenv(env),
    )
292
293
    return p.stdin, p.stdout, p.stderr, p

294

295
296
def pipefilter(s, cmd):
    '''filter string S through command CMD, returning its output'''
297
298
299
300
301
302
303
    p = subprocess.Popen(
        tonativestr(cmd),
        shell=True,
        close_fds=closefds,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
    )
304
305
306
    pout, perr = p.communicate(s)
    return pout

307

308
def tempfilter(s, cmd):
durin42's avatar
durin42 committed
309
    """filter string S through a pair of temporary files with CMD.
310
311
    CMD is used as a template to create the real command to be run,
    with the strings INFILE and OUTFILE replaced by the real names of
durin42's avatar
durin42 committed
312
    the temporary files generated."""
313
314
    inname, outname = None, None
    try:
315
        infd, inname = pycompat.mkstemp(prefix=b'hg-filter-in-')
316
        fp = os.fdopen(infd, 'wb')
317
318
        fp.write(s)
        fp.close()
319
        outfd, outname = pycompat.mkstemp(prefix=b'hg-filter-out-')
320
        os.close(outfd)
321
322
        cmd = cmd.replace(b'INFILE', inname)
        cmd = cmd.replace(b'OUTFILE', outname)
323
        code = system(cmd)
324
        if pycompat.sysplatform == b'OpenVMS' and code & 1:
325
326
            code = 0
        if code:
327
            raise error.Abort(
328
                _(b"command '%s' failed: %s") % (cmd, explainexit(code))
329
            )
330
        with open(outname, b'rb') as fp:
331
332
333
334
335
336
337
338
339
340
341
342
343
            return fp.read()
    finally:
        try:
            if inname:
                os.unlink(inname)
        except OSError:
            pass
        try:
            if outname:
                os.unlink(outname)
        except OSError:
            pass

344

345
_filtertable = {
346
347
    b'tempfile:': tempfilter,
    b'pipe:': pipefilter,
348
349
}

350

351
def filter(s, cmd):
352
353
    """filter a string through a command that transforms its input to its
    output"""
354
    for name, fn in pycompat.iteritems(_filtertable):
355
        if cmd.startswith(name):
356
            return fn(s, cmd[len(name) :].lstrip())
357
358
    return pipefilter(s, cmd)

359

360
361
_hgexecutable = None

362

363
364
365
366
367
368
def hgexecutable():
    """return location of the 'hg' executable.

    Defaults to $HG or 'hg' in the search path.
    """
    if _hgexecutable is None:
369
        hg = encoding.environ.get(b'HG')
370
        mainmod = sys.modules['__main__']
371
372
        if hg:
            _sethgexecutable(hg)
373
        elif resourceutil.mainfrozen():
374
            if getattr(sys, 'frozen', None) == 'macosx_app':
375
                # Env variable set by py2app
376
                _sethgexecutable(encoding.environ[b'EXECUTABLEPATH'])
377
378
            else:
                _sethgexecutable(pycompat.sysexecutable)
379
380
        elif (
            not pycompat.iswindows
381
            and os.path.basename(getattr(mainmod, '__file__', '')) == 'hg'
382
        ):
383
384
            _sethgexecutable(pycompat.fsencode(mainmod.__file__))
        else:
385
            _sethgexecutable(
386
                findexe(b'hg') or os.path.basename(pycompat.sysargv[0])
387
            )
388
389
    return _hgexecutable

390

391
392
393
394
395
def _sethgexecutable(path):
    """set location of the 'hg' executable"""
    global _hgexecutable
    _hgexecutable = path

396

397
398
399
400
401
def _testfileno(f, stdf):
    fileno = getattr(f, 'fileno', None)
    try:
        return fileno and fileno() == stdf.fileno()
    except io.UnsupportedOperation:
402
403
        return False  # fileno() raised UnsupportedOperation

404
405
406
407

def isstdin(f):
    return _testfileno(f, sys.__stdin__)

408

409
410
411
def isstdout(f):
    return _testfileno(f, sys.__stdout__)

412

413
def protectstdio(uin, uout):
414
415
416
417
    """Duplicate streams and redirect original if (uin, uout) are stdio

    If uin is stdin, it's redirected to /dev/null. If uout is stdout, it's
    redirected to stderr so the output is still readable.
418
419
420
421
422
423

    Returns (fin, fout) which point to the original (uin, uout) fds, but
    may be copy of (uin, uout). The returned streams can be considered
    "owned" in that print(), exec(), etc. never reach to them.
    """
    uout.flush()
424
    fin, fout = uin, uout
425
    if _testfileno(uin, stdin):
426
        newfd = os.dup(uin.fileno())
427
        nullfd = os.open(os.devnull, os.O_RDONLY)
428
        os.dup2(nullfd, uin.fileno())
429
        os.close(nullfd)
430
        fin = os.fdopen(newfd, 'rb')
431
    if _testfileno(uout, stdout):
432
        newfd = os.dup(uout.fileno())
433
        os.dup2(stderr.fileno(), uout.fileno())
434
        fout = os.fdopen(newfd, 'wb')
435
    return fin, fout
436

437

438
439
440
441
442
443
444
445
def restorestdio(uin, uout, fin, fout):
    """Restore (uin, uout) streams from possibly duplicated (fin, fout)"""
    uout.flush()
    for f, uif in [(fin, uin), (fout, uout)]:
        if f is not uif:
            os.dup2(f.fileno(), uif.fileno())
            f.close()

446

447
448
def shellenviron(environ=None):
    """return environ with optional override, useful for shelling out"""
449

450
    def py2shell(val):
451
        """convert python object into string that is useful to shell"""
452
        if val is None or val is False:
453
            return b'0'
454
        if val is True:
455
            return b'1'
456
        return pycompat.bytestr(val)
457

458
459
    env = dict(encoding.environ)
    if environ:
460
        env.update((k, py2shell(v)) for k, v in pycompat.iteritems(environ))
461
    env[b'HG'] = hgexecutable()
462
463
    return env

464

465
if pycompat.iswindows:
466

467
    def shelltonative(cmd, env):
468
469
470
        return platform.shelltocmdexe(  # pytype: disable=module-attr
            cmd, shellenviron(env)
        )
471
472

    tonativestr = encoding.strfromlocal
473
else:
474

475
476
477
    def shelltonative(cmd, env):
        return cmd

478
479
    tonativestr = pycompat.identity

480

481
def tonativeenv(env):
durin42's avatar
durin42 committed
482
    """convert the environment from bytes to strings suitable for Popen(), etc."""
483
484
    return pycompat.rapply(tonativestr, env)

485

486
def system(cmd, environ=None, cwd=None, out=None):
durin42's avatar
durin42 committed
487
    """enhanced shell command execution.
488
489
490
    run with environment maybe modified, maybe in different dir.

    if out is specified, it is assumed to be a file-like object that has a
durin42's avatar
durin42 committed
491
    write() method. stdout and stderr will be redirected to out."""
492
493
494
495
496
497
    try:
        stdout.flush()
    except Exception:
        pass
    env = shellenviron(environ)
    if out is None or isstdout(out):
498
499
500
501
502
503
504
        rc = subprocess.call(
            tonativestr(cmd),
            shell=True,
            close_fds=closefds,
            env=tonativeenv(env),
            cwd=pycompat.rapply(tonativestr, cwd),
        )
505
    else:
506
507
508
509
510
511
512
513
514
        proc = subprocess.Popen(
            tonativestr(cmd),
            shell=True,
            close_fds=closefds,
            env=tonativeenv(env),
            cwd=pycompat.rapply(tonativestr, cwd),
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
        )
515
        for line in iter(proc.stdout.readline, b''):
516
517
518
            out.write(line)
        proc.wait()
        rc = proc.returncode
519
    if pycompat.sysplatform == b'OpenVMS' and rc & 1:
520
521
522
        rc = 0
    return rc

523

524
525
526
527
_is_gui = None


def _gui():
528
529
    '''Are we running in a GUI?'''
    if pycompat.isdarwin:
530
        if b'SSH_CONNECTION' in encoding.environ:
531
532
533
534
535
536
537
538
539
            # handle SSH access to a box where the user is logged in
            return False
        elif getattr(osutil, 'isgui', None):
            # check if a CoreGraphics session is available
            return osutil.isgui()
        else:
            # pure build; use a safe default
            return True
    else:
540
        return pycompat.iswindows or encoding.environ.get(b"DISPLAY")
541

542

543
544
545
546
547
548
549
def gui():
    global _is_gui
    if _is_gui is None:
        _is_gui = _gui()
    return _is_gui


550
551
552
553
554
555
556
def hgcmd():
    """Return the command used to execute current hg

    This is different from hgexecutable() because on Windows we want
    to avoid things opening new shell windows like batch files, so we
    get either the python call or current executable.
    """
557
    if resourceutil.mainfrozen():
558
        if getattr(sys, 'frozen', None) == 'macosx_app':
559
            # Env variable set by py2app
560
            return [encoding.environ[b'EXECUTABLEPATH']]
561
562
563
564
        else:
            return [pycompat.sysexecutable]
    return _gethgcmd()

565

566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
def rundetached(args, condfn):
    """Execute the argument list in a detached process.

    condfn is a callable which is called repeatedly and should return
    True once the child process is known to have started successfully.
    At this point, the child process PID is returned. If the child
    process fails to start or finishes before condfn() evaluates to
    True, return -1.
    """
    # Windows case is easier because the child process is either
    # successfully starting and validating the condition or exiting
    # on failure. We just poll on its PID. On Unix, if the child
    # process fails to start, it will be left in a zombie state until
    # the parent wait on it, which we cannot do since we expect a long
    # running process on success. Instead we listen for SIGCHLD telling
    # us our child process terminated.
    terminated = set()
583

584
585
    def handler(signum, frame):
        terminated.add(os.wait())
586

587
588
589
590
591
592
593
    prevhandler = None
    SIGCHLD = getattr(signal, 'SIGCHLD', None)
    if SIGCHLD is not None:
        prevhandler = signal.signal(SIGCHLD, handler)
    try:
        pid = spawndetached(args)
        while not condfn():
594
            if (pid in terminated or not testpid(pid)) and not condfn():
595
596
597
598
599
600
                return -1
            time.sleep(0.1)
        return pid
    finally:
        if prevhandler is not None:
            signal.signal(signal.SIGCHLD, prevhandler)
601

602

603
@contextlib.contextmanager
604
def uninterruptible(warn):
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
    """Inhibit SIGINT handling on a region of code.

    Note that if this is called in a non-main thread, it turns into a no-op.

    Args:
      warn: A callable which takes no arguments, and returns True if the
            previous signal handling should be restored.
    """

    oldsiginthandler = [signal.getsignal(signal.SIGINT)]
    shouldbail = []

    def disabledsiginthandler(*args):
        if warn():
            signal.signal(signal.SIGINT, oldsiginthandler[0])
            del oldsiginthandler[0]
        shouldbail.append(True)

    try:
        try:
            signal.signal(signal.SIGINT, disabledsiginthandler)
        except ValueError:
            # wrong thread, oh well, we tried
            del oldsiginthandler[0]
        yield
    finally:
        if oldsiginthandler:
            signal.signal(signal.SIGINT, oldsiginthandler[0])
        if shouldbail:
            raise KeyboardInterrupt
635

636

637
638
639
640
641
if pycompat.iswindows:
    # no fork on Windows, but we can create a detached process
    # https://msdn.microsoft.com/en-us/library/windows/desktop/ms684863.aspx
    # No stdlib constant exists for this value
    DETACHED_PROCESS = 0x00000008
642
643
644
    # Following creation flags might create a console GUI window.
    # Using subprocess.CREATE_NEW_CONSOLE might helps.
    # See https://phab.mercurial-scm.org/D1701 for discussion
645
646
647
648
    _creationflags = (
        DETACHED_PROCESS
        | subprocess.CREATE_NEW_PROCESS_GROUP  # pytype: disable=module-attr
    )
649

650
    def runbgcommand(
651
652
653
654
655
656
657
        script,
        env,
        shell=False,
        stdout=None,
        stderr=None,
        ensurestart=True,
        record_wait=None,
658
        stdin_bytes=None,
659
    ):
660
661
662
        '''Spawn a command without waiting for it to finish.'''
        # we can't use close_fds *and* redirect stdin. I'm not sure that we
        # need to because the detached process has no console connection.
663
664
665
666
667
668
669
670
671
672

        try:
            stdin = None
            if stdin_bytes is not None:
                stdin = pycompat.unnamedtempfile()
                stdin.write(stdin_bytes)
                stdin.flush()
                stdin.seek(0)

            p = subprocess.Popen(
Augie Fackler's avatar
Augie Fackler committed
673
                pycompat.rapply(tonativestr, script),
674
675
676
677
678
679
680
681
682
683
684
685
686
                shell=shell,
                env=tonativeenv(env),
                close_fds=True,
                creationflags=_creationflags,
                stdin=stdin,
                stdout=stdout,
                stderr=stderr,
            )
            if record_wait is not None:
                record_wait(p.wait)
        finally:
            if stdin is not None:
                stdin.close()
687
688


689
else:
690

691
    def runbgcommand(
692
693
694
695
696
697
698
        cmd,
        env,
        shell=False,
        stdout=None,
        stderr=None,
        ensurestart=True,
        record_wait=None,
699
        stdin_bytes=None,
700
    ):
durin42's avatar
durin42 committed
701
        """Spawn a command without waiting for it to finish.
702
703
704
705
706
707


        When `record_wait` is not None, the spawned process will not be fully
        detached and the `record_wait` argument will be called with a the
        `Subprocess.wait` function for the spawned process.  This is mostly
        useful for developers that need to make sure the spawned process
durin42's avatar
durin42 committed
708
        finished before a certain point. (eg: writing test)"""
709
710
711
712
713
        if pycompat.isdarwin:
            # avoid crash in CoreFoundation in case another thread
            # calls gui() while we're calling fork().
            gui()

714
715
        # double-fork to completely detach from the parent process
        # based on http://code.activestate.com/recipes/278731
716
717
718
719
        if record_wait is None:
            pid = os.fork()
            if pid:
                if not ensurestart:
720
721
722
723
724
725
726
                    # Even though we're not waiting on the child process,
                    # we still must call waitpid() on it at some point so
                    # it's not a zombie/defunct. This is especially relevant for
                    # chg since the parent process won't die anytime soon.
                    # We use a thread to make the overhead tiny.
                    def _do_wait():
                        os.waitpid(pid, 0)
727

728
729
730
                    t = threading.Thread(target=_do_wait)
                    t.daemon = True
                    t.start()
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
                    return
                # Parent process
                (_pid, status) = os.waitpid(pid, 0)
                if os.WIFEXITED(status):
                    returncode = os.WEXITSTATUS(status)
                else:
                    returncode = -(os.WTERMSIG(status))
                if returncode != 0:
                    # The child process's return code is 0 on success, an errno
                    # value on failure, or 255 if we don't have a valid errno
                    # value.
                    #
                    # (It would be slightly nicer to return the full exception info
                    # over a pipe as the subprocess module does.  For now it
                    # doesn't seem worth adding that complexity here, though.)
                    if returncode == 255:
                        returncode = errno.EINVAL
                    raise OSError(
                        returncode,
                        b'error running %r: %s'
                        % (cmd, os.strerror(returncode)),
                    )
753
                return
754
755
756

        returncode = 255
        try:
757
758
759
            if record_wait is None:
                # Start a new session
                os.setsid()
760
761
762
763
764
765
766
767
768
            # connect stdin to devnull to make sure the subprocess can't
            # muck up that stream for mercurial.
            if stdin_bytes is None:
                stdin = open(os.devnull, b'r')
            else:
                stdin = pycompat.unnamedtempfile()
                stdin.write(stdin_bytes)
                stdin.flush()
                stdin.seek(0)
769
770

            if stdout is None:
771
                stdout = open(os.devnull, b'w')
772
            if stderr is None:
773
                stderr = open(os.devnull, b'w')
774

775
            p = subprocess.Popen(
776
777
778
779
780
781
782
783
                cmd,
                shell=shell,
                env=env,
                close_fds=True,
                stdin=stdin,
                stdout=stdout,
                stderr=stderr,
            )
784
785
            if record_wait is not None:
                record_wait(p.wait)
786
787
            returncode = 0
        except EnvironmentError as ex:
788
            returncode = ex.errno & 0xFF
789
790
791
792
793
794
795
796
797
            if returncode == 0:
                # This shouldn't happen, but just in case make sure the
                # return code is never 0 here.
                returncode = 255
        except Exception:
            returncode = 255
        finally:
            # mission accomplished, this child needs to exit and not
            # continue the hg process here.
798
            stdin.close()
799
800
            if record_wait is None:
                os._exit(returncode)