OILS / core / process.py View on Github | oils.pub

2125 lines, 1014 significant
1# Copyright 2016 Andy Chu. All rights reserved.
2# Licensed under the Apache License, Version 2.0 (the "License");
3# you may not use this file except in compliance with the License.
4# You may obtain a copy of the License at
5#
6# http://www.apache.org/licenses/LICENSE-2.0
7"""
8process.py - Launch processes and manipulate file descriptors.
9"""
10from __future__ import print_function
11
12from errno import EACCES, EBADF, ECHILD, EINTR, ENOENT, ENOEXEC, EEXIST
13import fcntl as fcntl_
14from fcntl import F_DUPFD, F_GETFD, F_SETFD, FD_CLOEXEC
15from signal import (SIG_DFL, SIG_IGN, SIGINT, SIGPIPE, SIGQUIT, SIGTSTP,
16 SIGTTOU, SIGTTIN, SIGWINCH)
17
18from _devbuild.gen.id_kind_asdl import Id
19from _devbuild.gen.runtime_asdl import (job_state_e, job_state_t,
20 job_state_str, wait_status,
21 wait_status_t, RedirValue,
22 redirect_arg, redirect_arg_e, trace,
23 trace_t)
24from _devbuild.gen.syntax_asdl import (
25 loc_t,
26 redir_loc,
27 redir_loc_e,
28 redir_loc_t,
29)
30from _devbuild.gen.value_asdl import (value, value_e)
31from core import dev
32from core import error
33from core.error import e_die
34from core import pyutil
35from core import pyos
36from core import state
37from display import ui
38from core import util
39from data_lang import j8_lite
40from frontend import location
41from frontend import match
42from mycpp import iolib
43from mycpp import mylib
44from mycpp.mylib import log, print_stderr, probe, tagswitch, iteritems
45
46import posix_ as posix
47from posix_ import (
48 # translated by mycpp and directly called! No wrapper!
49 WIFSIGNALED,
50 WIFEXITED,
51 WIFSTOPPED,
52 WEXITSTATUS,
53 WSTOPSIG,
54 WTERMSIG,
55 WNOHANG,
56 O_APPEND,
57 O_CREAT,
58 O_EXCL,
59 O_NONBLOCK,
60 O_NOCTTY,
61 O_RDONLY,
62 O_RDWR,
63 O_WRONLY,
64 O_TRUNC,
65)
66
67from typing import IO, List, Tuple, Dict, Optional, Any, cast, TYPE_CHECKING
68
69if TYPE_CHECKING:
70 from _devbuild.gen.runtime_asdl import cmd_value
71 from _devbuild.gen.syntax_asdl import command_t
72 from builtin import trap_osh
73 from core import optview
74 from core.util import _DebugFile
75 from osh.cmd_eval import CommandEvaluator
76
77NO_FD = -1
78
79# Minimum file descriptor that the shell can use. Other descriptors can be
80# directly used by user programs, e.g. exec 9>&1
81#
82# Oils uses 100 because users are allowed TWO digits in frontend/lexer_def.py.
83# This is a compromise between bash (unlimited, but requires crazy
84# bookkeeping), and dash/zsh (10) and mksh (24)
85_SHELL_MIN_FD = 100
86
87# Style for 'jobs' builtin
88STYLE_DEFAULT = 0
89STYLE_LONG = 1
90STYLE_PID_ONLY = 2
91
92# To save on allocations in JobList::GetJobWithSpec()
93CURRENT_JOB_SPECS = ['', '%', '%%', '%+']
94
95
96class ctx_FileCloser(object):
97
98 def __init__(self, f):
99 # type: (mylib.LineReader) -> None
100 self.f = f
101
102 def __enter__(self):
103 # type: () -> None
104 pass
105
106 def __exit__(self, type, value, traceback):
107 # type: (Any, Any, Any) -> None
108 self.f.close()
109
110
111def InitInteractiveShell(signal_safe):
112 # type: (iolib.SignalSafe) -> None
113 """Called when initializing an interactive shell."""
114
115 # The shell itself should ignore Ctrl-\.
116 iolib.sigaction(SIGQUIT, SIG_IGN)
117
118 # This prevents Ctrl-Z from suspending OSH in interactive mode.
119 iolib.sigaction(SIGTSTP, SIG_IGN)
120
121 # More signals from
122 # https://www.gnu.org/software/libc/manual/html_node/Initializing-the-Shell.html
123 # (but not SIGCHLD)
124 iolib.sigaction(SIGTTOU, SIG_IGN)
125 iolib.sigaction(SIGTTIN, SIG_IGN)
126
127 # Register a callback to receive terminal width changes.
128 # NOTE: In line_input.c, we turned off rl_catch_sigwinch.
129
130 # This is ALWAYS on, which means that it can cause EINTR, and wait() and
131 # read() have to handle it
132 iolib.RegisterSignalInterest(SIGWINCH)
133
134
135def SaveFd(fd):
136 # type: (int) -> int
137 saved = fcntl_.fcntl(fd, F_DUPFD, _SHELL_MIN_FD) # type: int
138 return saved
139
140
141class _RedirFrame(object):
142
143 def __init__(self, saved_fd, orig_fd, forget):
144 # type: (int, int, bool) -> None
145 self.saved_fd = saved_fd
146 self.orig_fd = orig_fd
147 self.forget = forget
148
149
150class _FdFrame(object):
151
152 def __init__(self):
153 # type: () -> None
154 self.saved = [] # type: List[_RedirFrame]
155 self.need_wait = [] # type: List[Process]
156
157 def Forget(self):
158 # type: () -> None
159 """For exec 1>&2."""
160 for rf in reversed(self.saved):
161 if rf.saved_fd != NO_FD and rf.forget:
162 posix.close(rf.saved_fd)
163
164 del self.saved[:] # like list.clear() in Python 3.3
165 del self.need_wait[:]
166
167 def __repr__(self):
168 # type: () -> str
169 return '<_FdFrame %s>' % self.saved
170
171
172class FdState(object):
173 """File descriptor state for the current process.
174
175 For example, you can do 'myfunc > out.txt' without forking. Child
176 processes inherit our state.
177 """
178
179 def __init__(
180 self,
181 errfmt, # type: ui.ErrorFormatter
182 job_control, # type: JobControl
183 job_list, # type: JobList
184 mem, # type: state.Mem
185 tracer, # type: Optional[dev.Tracer]
186 waiter, # type: Optional[Waiter]
187 exec_opts, # type: optview.Exec
188 ):
189 # type: (...) -> None
190 """
191 Args:
192 errfmt: for errors
193 job_list: For keeping track of _HereDocWriterThunk
194 """
195 self.errfmt = errfmt
196 self.job_control = job_control
197 self.job_list = job_list
198 self.cur_frame = _FdFrame() # for the top level
199 self.stack = [self.cur_frame]
200 self.mem = mem
201 self.tracer = tracer
202 self.waiter = waiter
203 self.exec_opts = exec_opts
204
205 def Open(self, path):
206 # type: (str) -> mylib.LineReader
207 """Opens a path for read, but moves it out of the reserved 3-9 fd
208 range.
209
210 Returns:
211 A Python file object. The caller is responsible for Close().
212
213 Raises:
214 IOError or OSError if the path can't be found. (This is Python-induced wart)
215 """
216 fd_mode = O_RDONLY
217 f = self._Open(path, 'r', fd_mode)
218
219 # Hacky downcast
220 return cast('mylib.LineReader', f)
221
222 # used for util.DebugFile
223 def OpenForWrite(self, path):
224 # type: (str) -> mylib.Writer
225 fd_mode = O_CREAT | O_RDWR
226 f = self._Open(path, 'w', fd_mode)
227
228 # Hacky downcast
229 return cast('mylib.Writer', f)
230
231 def _Open(self, path, c_mode, fd_mode):
232 # type: (str, str, int) -> IO[str]
233 fd = posix.open(path, fd_mode, 0o666) # may raise OSError
234
235 # Immediately move it to a new location
236 new_fd = SaveFd(fd)
237 posix.close(fd)
238
239 # Return a Python file handle
240 f = posix.fdopen(new_fd, c_mode) # may raise IOError
241 return f
242
243 def _WriteFdToMem(self, fd_name, fd):
244 # type: (str, int) -> None
245 if self.mem:
246 # setvar, not setref
247 state.OshLanguageSetValue(self.mem, location.LName(fd_name),
248 value.Str(str(fd)))
249
250 def _ReadFdFromMem(self, fd_name):
251 # type: (str) -> int
252 val = self.mem.GetValue(fd_name)
253 if val.tag() == value_e.Str:
254 try:
255 return int(cast(value.Str, val).s)
256 except ValueError:
257 return NO_FD
258 return NO_FD
259
260 def _PushSave(self, fd):
261 # type: (int) -> bool
262 """Save fd to a new location and remember to restore it later."""
263 #log('---- _PushSave %s', fd)
264 ok = True
265 try:
266 new_fd = SaveFd(fd)
267 except (IOError, OSError) as e:
268 ok = False
269 # Example program that causes this error: exec 4>&1. Descriptor 4 isn't
270 # open.
271 # This seems to be ignored in dash too in savefd()?
272 if e.errno != EBADF:
273 raise
274 if ok:
275 posix.close(fd)
276 fcntl_.fcntl(new_fd, F_SETFD, FD_CLOEXEC)
277 self.cur_frame.saved.append(_RedirFrame(new_fd, fd, True))
278 else:
279 # if we got EBADF, we still need to close the original on Pop()
280 self._PushClose(fd)
281
282 return ok
283
284 def _PushDup(self, fd1, blame_loc):
285 # type: (int, redir_loc_t) -> int
286 """Save fd2 in a higher range, and dup fd1 onto fd2.
287
288 Returns whether F_DUPFD/dup2 succeeded, and the new descriptor.
289 """
290 UP_loc = blame_loc
291 if blame_loc.tag() == redir_loc_e.VarName:
292 fd2_name = cast(redir_loc.VarName, UP_loc).name
293 try:
294 # F_DUPFD: GREATER than range
295 new_fd = fcntl_.fcntl(fd1, F_DUPFD, _SHELL_MIN_FD) # type: int
296 except (IOError, OSError) as e:
297 if e.errno == EBADF:
298 print_stderr('F_DUPFD fd %d: %s' %
299 (fd1, pyutil.strerror(e)))
300 return NO_FD
301 else:
302 raise # this redirect failed
303
304 self._WriteFdToMem(fd2_name, new_fd)
305
306 elif blame_loc.tag() == redir_loc_e.Fd:
307 fd2 = cast(redir_loc.Fd, UP_loc).fd
308
309 if fd1 == fd2:
310 # The user could have asked for it to be open on descriptor 3, but open()
311 # already returned 3, e.g. echo 3>out.txt
312 return NO_FD
313
314 # Check the validity of fd1 before _PushSave(fd2)
315 try:
316 fcntl_.fcntl(fd1, F_GETFD)
317 except (IOError, OSError) as e:
318 print_stderr('F_GETFD fd %d: %s' % (fd1, pyutil.strerror(e)))
319 raise
320
321 need_restore = self._PushSave(fd2)
322
323 #log('==== dup2 %s %s\n' % (fd1, fd2))
324 try:
325 posix.dup2(fd1, fd2)
326 except (IOError, OSError) as e:
327 # bash/dash give this error too, e.g. for 'echo hi 1>&3'
328 print_stderr('dup2(%d, %d): %s' %
329 (fd1, fd2, pyutil.strerror(e)))
330
331 # Restore and return error
332 if need_restore:
333 rf = self.cur_frame.saved.pop()
334 posix.dup2(rf.saved_fd, rf.orig_fd)
335 posix.close(rf.saved_fd)
336
337 raise # this redirect failed
338
339 new_fd = fd2
340
341 else:
342 raise AssertionError()
343
344 return new_fd
345
346 def _PushCloseFd(self, blame_loc):
347 # type: (redir_loc_t) -> bool
348 """For 2>&-"""
349 # exec {fd}>&- means close the named descriptor
350
351 UP_loc = blame_loc
352 if blame_loc.tag() == redir_loc_e.VarName:
353 fd_name = cast(redir_loc.VarName, UP_loc).name
354 fd = self._ReadFdFromMem(fd_name)
355 if fd == NO_FD:
356 return False
357
358 elif blame_loc.tag() == redir_loc_e.Fd:
359 fd = cast(redir_loc.Fd, UP_loc).fd
360
361 else:
362 raise AssertionError()
363
364 self._PushSave(fd)
365
366 return True
367
368 def _PushClose(self, fd):
369 # type: (int) -> None
370 self.cur_frame.saved.append(_RedirFrame(NO_FD, fd, False))
371
372 def _PushWait(self, proc):
373 # type: (Process) -> None
374 self.cur_frame.need_wait.append(proc)
375
376 def _ApplyRedirect(self, r):
377 # type: (RedirValue) -> None
378 arg = r.arg
379 UP_arg = arg
380 with tagswitch(arg) as case:
381
382 if case(redirect_arg_e.Path):
383 arg = cast(redirect_arg.Path, UP_arg)
384 # noclobber flag is OR'd with other flags when allowed
385 noclobber_mode = O_EXCL if self.exec_opts.noclobber() else 0
386 if r.op_id in (Id.Redir_Great, Id.Redir_AndGreat): # > &>
387 # NOTE: This is different than >| because it respects noclobber, but
388 # that option is almost never used. See test/wild.sh.
389 mode = O_CREAT | O_WRONLY | O_TRUNC | noclobber_mode
390 elif r.op_id == Id.Redir_Clobber: # >|
391 mode = O_CREAT | O_WRONLY | O_TRUNC
392 elif r.op_id in (Id.Redir_DGreat,
393 Id.Redir_AndDGreat): # >> &>>
394 mode = O_CREAT | O_WRONLY | O_APPEND | noclobber_mode
395 elif r.op_id == Id.Redir_Less: # <
396 mode = O_RDONLY
397 elif r.op_id == Id.Redir_LessGreat: # <>
398 mode = O_CREAT | O_RDWR
399 else:
400 raise NotImplementedError(r.op_id)
401
402 # NOTE: 0666 is affected by umask, all shells use it.
403 try:
404 open_fd = posix.open(arg.filename, mode, 0o666)
405 except (IOError, OSError) as e:
406 if e.errno == EEXIST and self.exec_opts.noclobber():
407 extra = ' (noclobber)'
408 else:
409 extra = ''
410 self.errfmt.Print_(
411 "Can't open %r: %s%s" %
412 (arg.filename, pyutil.strerror(e), extra),
413 blame_loc=r.op_loc)
414 raise # redirect failed
415
416 new_fd = self._PushDup(open_fd, r.loc)
417 if new_fd != NO_FD:
418 posix.close(open_fd)
419
420 # Now handle &> and &>> and their variants. These pairs are the same:
421 #
422 # stdout_stderr.py &> out-err.txt
423 # stdout_stderr.py > out-err.txt 2>&1
424 #
425 # stdout_stderr.py 3&> out-err.txt
426 # stdout_stderr.py 3> out-err.txt 2>&3
427 #
428 # Ditto for {fd}> and {fd}&>
429
430 if r.op_id in (Id.Redir_AndGreat, Id.Redir_AndDGreat):
431 self._PushDup(new_fd, redir_loc.Fd(2))
432
433 elif case(redirect_arg_e.CopyFd): # e.g. echo hi 1>&2
434 arg = cast(redirect_arg.CopyFd, UP_arg)
435
436 if r.op_id == Id.Redir_GreatAnd: # 1>&2
437 self._PushDup(arg.target_fd, r.loc)
438
439 elif r.op_id == Id.Redir_LessAnd: # 0<&5
440 # The only difference between >& and <& is the default file
441 # descriptor argument.
442 self._PushDup(arg.target_fd, r.loc)
443
444 else:
445 raise NotImplementedError()
446
447 elif case(redirect_arg_e.MoveFd): # e.g. echo hi 5>&6-
448 arg = cast(redirect_arg.MoveFd, UP_arg)
449 new_fd = self._PushDup(arg.target_fd, r.loc)
450 if new_fd != NO_FD:
451 posix.close(arg.target_fd)
452
453 UP_loc = r.loc
454 if r.loc.tag() == redir_loc_e.Fd:
455 fd = cast(redir_loc.Fd, UP_loc).fd
456 else:
457 fd = NO_FD
458
459 self.cur_frame.saved.append(_RedirFrame(new_fd, fd, False))
460
461 elif case(redirect_arg_e.CloseFd): # e.g. echo hi 5>&-
462 self._PushCloseFd(r.loc)
463
464 elif case(redirect_arg_e.HereDoc):
465 arg = cast(redirect_arg.HereDoc, UP_arg)
466
467 # NOTE: Do these descriptors have to be moved out of the range 0-9?
468 read_fd, write_fd = posix.pipe()
469
470 self._PushDup(read_fd, r.loc) # stdin is now the pipe
471
472 # We can't close like we do in the filename case above? The writer can
473 # get a "broken pipe".
474 self._PushClose(read_fd)
475
476 thunk = _HereDocWriterThunk(write_fd, arg.body)
477
478 # Use PIPE_SIZE to save a process in the case of small here
479 # docs, which are the common case. (dash does this.)
480
481 # Note: could instrument this to see how often it happens.
482 # Though strace -ff can also work.
483 start_process = len(arg.body) > 4096
484 #start_process = True
485
486 if start_process:
487 here_proc = Process(thunk, self.job_control, self.job_list,
488 self.tracer)
489
490 # NOTE: we could close the read pipe here, but it doesn't really
491 # matter because we control the code.
492 here_proc.StartProcess(trace.HereDoc)
493 #log('Started %s as %d', here_proc, pid)
494 self._PushWait(here_proc)
495
496 # Now that we've started the child, close it in the parent.
497 posix.close(write_fd)
498
499 else:
500 posix.write(write_fd, arg.body)
501 posix.close(write_fd)
502
503 def Push(self, redirects, err_out):
504 # type: (List[RedirValue], List[error.IOError_OSError]) -> None
505 """Apply a group of redirects and remember to undo them."""
506
507 #log('> fd_state.Push %s', redirects)
508 new_frame = _FdFrame()
509 self.stack.append(new_frame)
510 self.cur_frame = new_frame
511
512 for r in redirects:
513 #log('apply %s', r)
514 with ui.ctx_Location(self.errfmt, r.op_loc):
515 try:
516 self._ApplyRedirect(r)
517 except (IOError, OSError) as e:
518 err_out.append(e)
519 # This can fail too
520 self.Pop(err_out)
521 return # for bad descriptor, etc.
522
523 def PushStdinFromPipe(self, r):
524 # type: (int) -> bool
525 """Save the current stdin and make it come from descriptor 'r'.
526
527 'r' is typically the read-end of a pipe. For 'lastpipe'/ZSH
528 semantics of
529
530 echo foo | read line; echo $line
531 """
532 new_frame = _FdFrame()
533 self.stack.append(new_frame)
534 self.cur_frame = new_frame
535
536 self._PushDup(r, redir_loc.Fd(0))
537 return True
538
539 def Pop(self, err_out):
540 # type: (List[error.IOError_OSError]) -> None
541 frame = self.stack.pop()
542 #log('< Pop %s', frame)
543 for rf in reversed(frame.saved):
544 if rf.saved_fd == NO_FD:
545 #log('Close %d', orig)
546 try:
547 posix.close(rf.orig_fd)
548 except (IOError, OSError) as e:
549 err_out.append(e)
550 log('Error closing descriptor %d: %s', rf.orig_fd,
551 pyutil.strerror(e))
552 return
553 else:
554 try:
555 posix.dup2(rf.saved_fd, rf.orig_fd)
556 except (IOError, OSError) as e:
557 err_out.append(e)
558 log('dup2(%d, %d) error: %s', rf.saved_fd, rf.orig_fd,
559 pyutil.strerror(e))
560 #log('fd state:')
561 #posix.system('ls -l /proc/%s/fd' % posix.getpid())
562 return
563 posix.close(rf.saved_fd)
564 #log('dup2 %s %s', saved, orig)
565
566 # Wait for here doc processes to finish.
567 for proc in frame.need_wait:
568 unused_status = proc.Wait(self.waiter)
569
570 def MakePermanent(self):
571 # type: () -> None
572 self.cur_frame.Forget()
573
574
575class ChildStateChange(object):
576
577 def __init__(self):
578 # type: () -> None
579 """Empty constructor for mycpp."""
580 pass
581
582 def Apply(self):
583 # type: () -> None
584 raise NotImplementedError()
585
586 def ApplyFromParent(self, proc):
587 # type: (Process) -> None
588 """Noop for all state changes other than SetPgid for mycpp."""
589 pass
590
591
592class StdinFromPipe(ChildStateChange):
593
594 def __init__(self, pipe_read_fd, w):
595 # type: (int, int) -> None
596 self.r = pipe_read_fd
597 self.w = w
598
599 def __repr__(self):
600 # type: () -> str
601 return '<StdinFromPipe %d %d>' % (self.r, self.w)
602
603 def Apply(self):
604 # type: () -> None
605 posix.dup2(self.r, 0)
606 posix.close(self.r) # close after dup
607
608 posix.close(self.w) # we're reading from the pipe, not writing
609 #log('child CLOSE w %d pid=%d', self.w, posix.getpid())
610
611
612class StdoutToPipe(ChildStateChange):
613
614 def __init__(self, r, pipe_write_fd):
615 # type: (int, int) -> None
616 self.r = r
617 self.w = pipe_write_fd
618
619 def __repr__(self):
620 # type: () -> str
621 return '<StdoutToPipe %d %d>' % (self.r, self.w)
622
623 def Apply(self):
624 # type: () -> None
625 posix.dup2(self.w, 1)
626 posix.close(self.w) # close after dup
627
628 posix.close(self.r) # we're writing to the pipe, not reading
629 #log('child CLOSE r %d pid=%d', self.r, posix.getpid())
630
631
632class StderrToPipe(ChildStateChange):
633
634 def __init__(self, r, pipe_write_fd):
635 # type: (int, int) -> None
636 self.r = r
637 self.w = pipe_write_fd
638
639 def __repr__(self):
640 # type: () -> str
641 return '<StderrToPipe %d %d>' % (self.r, self.w)
642
643 def Apply(self):
644 # type: () -> None
645 posix.dup2(self.w, 2)
646 posix.close(self.w) # close after dup
647
648 posix.close(self.r) # we're writing to the pipe, not reading
649 #log('child CLOSE r %d pid=%d', self.r, posix.getpid())
650
651
652INVALID_PGID = -1
653# argument to setpgid() that means the process is its own leader
654OWN_LEADER = 0
655
656
657class SetPgid(ChildStateChange):
658
659 def __init__(self, pgid, tracer):
660 # type: (int, dev.Tracer) -> None
661 self.pgid = pgid
662 self.tracer = tracer
663
664 def Apply(self):
665 # type: () -> None
666 try:
667 posix.setpgid(0, self.pgid)
668 except (IOError, OSError) as e:
669 self.tracer.OtherMessage(
670 'osh: child %d failed to set its process group to %d: %s' %
671 (posix.getpid(), self.pgid, pyutil.strerror(e)))
672
673 def ApplyFromParent(self, proc):
674 # type: (Process) -> None
675 try:
676 posix.setpgid(proc.pid, self.pgid)
677 except (IOError, OSError) as e:
678 self.tracer.OtherMessage(
679 'osh: parent failed to set process group for PID %d to %d: %s'
680 % (proc.pid, self.pgid, pyutil.strerror(e)))
681
682
683class ExternalProgram(object):
684 """The capability to execute an external program like 'ls'."""
685
686 def __init__(
687 self,
688 hijack_shebang, # type: str
689 fd_state, # type: FdState
690 errfmt, # type: ui.ErrorFormatter
691 debug_f, # type: _DebugFile
692 ):
693 # type: (...) -> None
694 """
695 Args:
696 hijack_shebang: The path of an interpreter to run instead of the one
697 specified in the shebang line. May be empty.
698 """
699 self.hijack_shebang = hijack_shebang
700 self.fd_state = fd_state
701 self.errfmt = errfmt
702 self.debug_f = debug_f
703
704 def Exec(self, argv0_path, cmd_val, environ):
705 # type: (str, cmd_value.Argv, Dict[str, str]) -> None
706 """Execute a program and exit this process.
707
708 Called by: ls / exec ls / ( ls / )
709 """
710 probe('process', 'ExternalProgram_Exec', argv0_path)
711 self._Exec(argv0_path, cmd_val.argv, cmd_val.arg_locs[0], environ,
712 True)
713 assert False, "This line should never execute" # NO RETURN
714
715 def _Exec(self, argv0_path, argv, argv0_loc, environ, should_retry):
716 # type: (str, List[str], loc_t, Dict[str, str], bool) -> None
717 if len(self.hijack_shebang):
718 opened = True
719 try:
720 f = self.fd_state.Open(argv0_path)
721 except (IOError, OSError) as e:
722 opened = False
723
724 if opened:
725 with ctx_FileCloser(f):
726 # Test if the shebang looks like a shell. TODO: The file might be
727 # binary with no newlines, so read 80 bytes instead of readline().
728
729 #line = f.read(80) # type: ignore # TODO: fix this
730 line = f.readline()
731
732 if match.ShouldHijack(line):
733 h_argv = [self.hijack_shebang, argv0_path]
734 h_argv.extend(argv[1:])
735 argv = h_argv
736 argv0_path = self.hijack_shebang
737 self.debug_f.writeln('Hijacked: %s' % argv0_path)
738 else:
739 #self.debug_f.log('Not hijacking %s (%r)', argv, line)
740 pass
741
742 try:
743 posix.execve(argv0_path, argv, environ)
744 except (IOError, OSError) as e:
745 # Run with /bin/sh when ENOEXEC error (no shebang). All shells do this.
746 if e.errno == ENOEXEC and should_retry:
747 new_argv = ['/bin/sh', argv0_path]
748 new_argv.extend(argv[1:])
749 self._Exec('/bin/sh', new_argv, argv0_loc, environ, False)
750 # NO RETURN
751
752 # Would be nice: when the path is relative and ENOENT: print PWD and do
753 # spelling correction?
754
755 self.errfmt.Print_(
756 "Can't execute %r: %s" % (argv0_path, pyutil.strerror(e)),
757 argv0_loc)
758
759 # POSIX mentions 126 and 127 for two specific errors. The rest are
760 # unspecified.
761 #
762 # http://pubs.opengroup.org/onlinepubs/9699919799.2016edition/utilities/V3_chap02.html#tag_18_08_02
763 if e.errno == EACCES:
764 status = 126
765 elif e.errno == ENOENT:
766 # TODO: most shells print 'command not found', rather than strerror()
767 # == "No such file or directory". That's better because it's at the
768 # end of the path search, and we're never searching for a directory.
769 status = 127
770 else:
771 # dash uses 2, but we use that for parse errors. This seems to be
772 # consistent with mksh and zsh.
773 status = 127
774
775 posix._exit(status)
776 # NO RETURN
777
778
779class Thunk(object):
780 """Abstract base class for things runnable in another process."""
781
782 def __init__(self):
783 # type: () -> None
784 """Empty constructor for mycpp."""
785 pass
786
787 def Run(self):
788 # type: () -> None
789 """Returns a status code."""
790 raise NotImplementedError()
791
792 def UserString(self):
793 # type: () -> str
794 """Display for the 'jobs' list."""
795 raise NotImplementedError()
796
797 def __repr__(self):
798 # type: () -> str
799 return self.UserString()
800
801
802class ExternalThunk(Thunk):
803 """An external executable."""
804
805 def __init__(self, ext_prog, argv0_path, cmd_val, environ):
806 # type: (ExternalProgram, str, cmd_value.Argv, Dict[str, str]) -> None
807 self.ext_prog = ext_prog
808 self.argv0_path = argv0_path
809 self.cmd_val = cmd_val
810 self.environ = environ
811
812 def UserString(self):
813 # type: () -> str
814
815 # NOTE: This is the format the Tracer uses.
816 # bash displays sleep $n & (code)
817 # but OSH displays sleep 1 & (argv array)
818 # We could switch the former but I'm not sure it's necessary.
819 tmp = [j8_lite.MaybeShellEncode(a) for a in self.cmd_val.argv]
820 return '[process] %s' % ' '.join(tmp)
821
822 def Run(self):
823 # type: () -> None
824 """An ExternalThunk is run in parent for the exec builtin."""
825 self.ext_prog.Exec(self.argv0_path, self.cmd_val, self.environ)
826
827
828class SubProgramThunk(Thunk):
829 """A subprogram that can be executed in another process."""
830
831 def __init__(
832 self,
833 cmd_ev, # type: CommandEvaluator
834 node, # type: command_t
835 trap_state, # type: trap_osh.TrapState
836 multi_trace, # type: dev.MultiTracer
837 inherit_errexit, # type: bool
838 inherit_errtrace, # type: bool
839 ):
840 # type: (...) -> None
841 self.cmd_ev = cmd_ev
842 self.node = node
843 self.trap_state = trap_state
844 self.multi_trace = multi_trace
845 self.inherit_errexit = inherit_errexit # for bash errexit compatibility
846 self.inherit_errtrace = inherit_errtrace # for bash errtrace compatibility
847
848 def UserString(self):
849 # type: () -> str
850
851 # NOTE: These can be pieces of a pipeline, so they're arbitrary nodes.
852 # TODO: Extract SPIDS from node to display source? Note that
853 # CompoundStatus also has locations of each pipeline component; see
854 # Executor.RunPipeline()
855 thunk_str = ui.CommandType(self.node)
856 return '[subprog] %s' % thunk_str
857
858 def Run(self):
859 # type: () -> None
860 #self.errfmt.OneLineErrExit() # don't quote code in child processes
861 probe('process', 'SubProgramThunk_Run')
862
863 # TODO: break circular dep. Bit flags could go in ASDL or headers.
864 from osh import cmd_eval
865
866 # signal handlers aren't inherited
867 self.trap_state.ClearForSubProgram(self.inherit_errtrace)
868
869 # NOTE: may NOT return due to exec().
870 if not self.inherit_errexit:
871 self.cmd_ev.mutable_opts.DisableErrExit()
872 try:
873 # optimize to eliminate redundant subshells like ( echo hi ) | wc -l etc.
874 self.cmd_ev.ExecuteAndCatch(
875 self.node,
876 cmd_eval.OptimizeSubshells | cmd_eval.MarkLastCommands)
877 status = self.cmd_ev.LastStatus()
878 # NOTE: We ignore the is_fatal return value. The user should set -o
879 # errexit so failures in subprocesses cause failures in the parent.
880 except util.UserExit as e:
881 status = e.status
882
883 # Handle errors in a subshell. These two cases are repeated from main()
884 # and the core/completion.py hook.
885 except KeyboardInterrupt:
886 print('')
887 status = 130 # 128 + 2
888 except (IOError, OSError) as e:
889 print_stderr('oils I/O error (subprogram): %s' %
890 pyutil.strerror(e))
891 status = 2
892
893 # If ProcessInit() doesn't turn off buffering, this is needed before
894 # _exit()
895 pyos.FlushStdout()
896
897 self.multi_trace.WriteDumps()
898
899 # We do NOT want to raise SystemExit here. Otherwise dev.Tracer::Pop()
900 # gets called in BOTH processes.
901 # The crash dump seems to be unaffected.
902 posix._exit(status)
903
904
905class _HereDocWriterThunk(Thunk):
906 """Write a here doc to one end of a pipe.
907
908 May be be executed in either a child process or the main shell
909 process.
910 """
911
912 def __init__(self, w, body_str):
913 # type: (int, str) -> None
914 self.w = w
915 self.body_str = body_str
916
917 def UserString(self):
918 # type: () -> str
919
920 # You can hit Ctrl-Z and the here doc writer will be suspended! Other
921 # shells don't have this problem because they use temp files! That's a bit
922 # unfortunate.
923 return '[here doc writer]'
924
925 def Run(self):
926 # type: () -> None
927 """do_exit: For small pipelines."""
928 probe('process', 'HereDocWriterThunk_Run')
929 #log('Writing %r', self.body_str)
930 posix.write(self.w, self.body_str)
931 #log('Wrote %r', self.body_str)
932 posix.close(self.w)
933 #log('Closed %d', self.w)
934
935 posix._exit(0)
936
937
938class Job(object):
939 """Interface for both Process and Pipeline.
940
941 They both can be put in the background and waited on.
942
943 Confusing thing about pipelines in the background: They have TOO MANY NAMES.
944
945 sleep 1 | sleep 2 &
946
947 - The LAST PID is what's printed at the prompt. This is $!, a PROCESS ID and
948 not a JOB ID.
949 # https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html#Special-Parameters
950 - The process group leader (setpgid) is the FIRST PID.
951 - It's also %1 or %+. The last job started.
952 """
953
954 def __init__(self):
955 # type: () -> None
956 # Initial state with & or Ctrl-Z is Running.
957 self.state = job_state_e.Running
958 self.job_id = -1
959 self.in_background = False
960
961 def DisplayJob(self, job_id, f, style):
962 # type: (int, mylib.Writer, int) -> None
963 raise NotImplementedError()
964
965 def State(self):
966 # type: () -> job_state_t
967 return self.state
968
969 def ProcessGroupId(self):
970 # type: () -> int
971 """Return the process group ID associated with this job."""
972 raise NotImplementedError()
973
974 def PidForWait(self):
975 # type: () -> int
976 """Return the pid we can wait on."""
977 raise NotImplementedError()
978
979 def JobWait(self, waiter):
980 # type: (Waiter) -> wait_status_t
981 """Wait for this process/pipeline to be stopped or finished."""
982 raise NotImplementedError()
983
984 def SetBackground(self):
985 # type: () -> None
986 """Record that this job is running in the background."""
987 self.in_background = True
988
989 def SetForeground(self):
990 # type: () -> None
991 """Record that this job is running in the foreground."""
992 self.in_background = False
993
994
995class Process(Job):
996 """A process to run.
997
998 TODO: Should we make it clear that this is a FOREGROUND process? A
999 background process is wrapped in a "job". It is unevaluated.
1000
1001 It provides an API to manipulate file descriptor state in parent and child.
1002 """
1003
1004 def __init__(self, thunk, job_control, job_list, tracer):
1005 # type: (Thunk, JobControl, JobList, dev.Tracer) -> None
1006 """
1007 Args:
1008 thunk: Thunk instance
1009 job_list: for process bookkeeping
1010 """
1011 Job.__init__(self)
1012 assert isinstance(thunk, Thunk), thunk
1013 self.thunk = thunk
1014 self.job_control = job_control
1015 self.job_list = job_list
1016 self.tracer = tracer
1017
1018 # For pipelines
1019 self.parent_pipeline = None # type: Pipeline
1020 self.state_changes = [] # type: List[ChildStateChange]
1021 self.close_r = -1
1022 self.close_w = -1
1023
1024 self.pid = -1
1025 self.status = -1
1026
1027 def Init_ParentPipeline(self, pi):
1028 # type: (Pipeline) -> None
1029 """For updating PIPESTATUS."""
1030 self.parent_pipeline = pi
1031
1032 def __repr__(self):
1033 # type: () -> str
1034
1035 # note: be wary of infinite mutual recursion
1036 #s = ' %s' % self.parent_pipeline if self.parent_pipeline else ''
1037 #return '<Process %s%s>' % (self.thunk, s)
1038 return '<Process pid=%d state=%s %s>' % (
1039 self.pid, _JobStateStr(self.state), self.thunk)
1040
1041 def ProcessGroupId(self):
1042 # type: () -> int
1043 """Returns the group ID of this process."""
1044 # This should only ever be called AFTER the process has started
1045 assert self.pid != -1
1046 if self.parent_pipeline:
1047 # XXX: Maybe we should die here instead? Unclear if this branch
1048 # should even be reachable with the current builtins.
1049 return self.parent_pipeline.ProcessGroupId()
1050
1051 return self.pid
1052
1053 def PidForWait(self):
1054 # type: () -> int
1055 """Return the pid we can wait on."""
1056 assert self.pid != -1
1057 return self.pid
1058
1059 def DisplayJob(self, job_id, f, style):
1060 # type: (int, mylib.Writer, int) -> None
1061 if job_id == -1:
1062 job_id_str = ' '
1063 else:
1064 job_id_str = '%%%d' % job_id
1065 if style == STYLE_PID_ONLY:
1066 f.write('%d\n' % self.pid)
1067 else:
1068 f.write('%s %d %7s ' %
1069 (job_id_str, self.pid, _JobStateStr(self.state)))
1070 f.write(self.thunk.UserString())
1071 f.write('\n')
1072
1073 def AddStateChange(self, s):
1074 # type: (ChildStateChange) -> None
1075 self.state_changes.append(s)
1076
1077 def AddPipeToClose(self, r, w):
1078 # type: (int, int) -> None
1079 self.close_r = r
1080 self.close_w = w
1081
1082 def MaybeClosePipe(self):
1083 # type: () -> None
1084 if self.close_r != -1:
1085 posix.close(self.close_r)
1086 posix.close(self.close_w)
1087
1088 def StartProcess(self, why):
1089 # type: (trace_t) -> int
1090 """Start this process with fork(), handling redirects."""
1091 pid = posix.fork()
1092 if pid < 0:
1093 # When does this happen?
1094 e_die('Fatal error in posix.fork()')
1095
1096 elif pid == 0: # child
1097 # Note: this happens in BOTH interactive and non-interactive shells.
1098 # We technically don't need to do most of it in non-interactive, since we
1099 # did not change state in InitInteractiveShell().
1100
1101 for st in self.state_changes:
1102 st.Apply()
1103
1104 # Python sets SIGPIPE handler to SIG_IGN by default. Child processes
1105 # shouldn't have this.
1106 # https://docs.python.org/2/library/signal.html
1107 # See Python/pythonrun.c.
1108 iolib.sigaction(SIGPIPE, SIG_DFL)
1109
1110 # Respond to Ctrl-\ (core dump)
1111 iolib.sigaction(SIGQUIT, SIG_DFL)
1112
1113 # Only standalone children should get Ctrl-Z. Pipelines remain in the
1114 # foreground because suspending them is difficult with our 'lastpipe'
1115 # semantics.
1116 pid = posix.getpid()
1117 if posix.getpgid(0) == pid and self.parent_pipeline is None:
1118 iolib.sigaction(SIGTSTP, SIG_DFL)
1119
1120 # More signals from
1121 # https://www.gnu.org/software/libc/manual/html_node/Launching-Jobs.html
1122 # (but not SIGCHLD)
1123 iolib.sigaction(SIGTTOU, SIG_DFL)
1124 iolib.sigaction(SIGTTIN, SIG_DFL)
1125
1126 self.tracer.OnNewProcess(pid)
1127 # clear foreground pipeline for subshells
1128 self.thunk.Run()
1129 # Never returns
1130
1131 #log('STARTED process %s, pid = %d', self, pid)
1132 self.tracer.OnProcessStart(pid, why)
1133
1134 # Class invariant: after the process is started, it stores its PID.
1135 self.pid = pid
1136
1137 # SetPgid needs to be applied from the child and the parent to avoid
1138 # racing in calls to tcsetpgrp() in the parent. See APUE sec. 9.2.
1139 for st in self.state_changes:
1140 st.ApplyFromParent(self)
1141
1142 # Program invariant: We keep track of every child process!
1143 # Waiter::WaitForOne() needs it to update state
1144 self.job_list.AddChildProcess(pid, self)
1145
1146 return pid
1147
1148 def Wait(self, waiter):
1149 # type: (Waiter) -> int
1150 """Wait for this Process to finish."""
1151 # Keep waiting if waitpid() was interrupted with a signal (unlike the
1152 # 'wait' builtin)
1153 while self.state == job_state_e.Running:
1154 result, _ = waiter.WaitForOne()
1155 if result == W1_NO_CHILDREN:
1156 break
1157
1158 # Cleanup - for background jobs this happens in the 'wait' builtin,
1159 # e.g. after JobWait()
1160 if self.state == job_state_e.Exited:
1161 self.job_list.PopChildProcess(self.pid)
1162
1163 assert self.status >= 0, self.status
1164 return self.status
1165
1166 def JobWait(self, waiter):
1167 # type: (Waiter) -> wait_status_t
1168 """Process::JobWait, called by wait builtin"""
1169 # wait builtin can be interrupted
1170 while self.state == job_state_e.Running:
1171 result, w1_arg = waiter.WaitForOne() # mutates self.state
1172
1173 if result == W1_CALL_INTR:
1174 return wait_status.Cancelled(w1_arg)
1175
1176 if result == W1_NO_CHILDREN:
1177 break
1178
1179 # Ignore W1_EXITED, W1_STOPPED - these are OTHER processes
1180
1181 assert self.status >= 0, self.status
1182 return wait_status.Proc(self.state, self.status)
1183
1184 def WhenStopped(self, stop_sig):
1185 # type: (int) -> None
1186 """Called by the Waiter when this Process is stopped."""
1187 # 128 is a shell thing
1188 # https://www.gnu.org/software/bash/manual/html_node/Exit-Status.html
1189 self.status = 128 + stop_sig
1190 self.state = job_state_e.Stopped
1191
1192 if self.parent_pipeline:
1193 # TODO: do we need anything here?
1194 # We need AllStopped() just like AllExited()?
1195
1196 #self.parent_pipeline.WhenPartIsStopped(pid, status)
1197 #return
1198 pass
1199
1200 if self.job_id == -1:
1201 # This process was started in the foreground, not with &. So it
1202 # was NOT a job, but after Ctrl-Z, it now a job.
1203 self.job_list.AddJob(self)
1204
1205 if not self.in_background:
1206 # e.g. sleep 5; then Ctrl-Z
1207 self.job_control.MaybeTakeTerminal()
1208 self.SetBackground()
1209
1210 def WhenExited(self, pid, status):
1211 # type: (int, int) -> None
1212 """Called by the Waiter when this Process exits."""
1213
1214 #log('Process WhenExited %d %d', pid, status)
1215 assert pid == self.pid, 'Expected %d, got %d' % (self.pid, pid)
1216 self.status = status
1217 self.state = job_state_e.Exited
1218
1219 if self.parent_pipeline:
1220 # populate pipeline status array; update Pipeline state, etc.
1221 self.parent_pipeline.WhenPartExited(pid, status)
1222 return
1223
1224 if self.job_id != -1:
1225 # Job might have been brought to the foreground after being
1226 # assigned a job ID.
1227 if self.in_background:
1228 # the main loop calls PollNotifications(), WaitForOne(),
1229 # which results in this
1230 # TODO: only print this interactively, like other shells
1231 print_stderr('[%%%d] PID %d Done' % (self.job_id, self.pid))
1232
1233 if not self.in_background:
1234 self.job_control.MaybeTakeTerminal()
1235
1236 def RunProcess(self, waiter, why):
1237 # type: (Waiter, trace_t) -> int
1238 """Run this process synchronously."""
1239 self.StartProcess(why)
1240 # ShellExecutor might be calling this for the last part of a pipeline.
1241 if self.parent_pipeline is None:
1242 # QUESTION: Can the PGID of a single process just be the PID? i.e. avoid
1243 # calling getpgid()?
1244 self.job_control.MaybeGiveTerminal(posix.getpgid(self.pid))
1245 return self.Wait(waiter)
1246
1247
1248class ctx_Pipe(object):
1249
1250 def __init__(self, fd_state, fd, err_out):
1251 # type: (FdState, int, List[error.IOError_OSError]) -> None
1252 fd_state.PushStdinFromPipe(fd)
1253 self.fd_state = fd_state
1254 self.err_out = err_out
1255
1256 def __enter__(self):
1257 # type: () -> None
1258 pass
1259
1260 def __exit__(self, type, value, traceback):
1261 # type: (Any, Any, Any) -> None
1262 self.fd_state.Pop(self.err_out)
1263
1264
1265class Pipeline(Job):
1266 """A pipeline of processes to run.
1267
1268 Cases we handle:
1269
1270 foo | bar
1271 $(foo | bar)
1272 foo | bar | read v
1273 """
1274
1275 def __init__(self, sigpipe_status_ok, job_control, job_list, tracer):
1276 # type: (bool, JobControl, JobList, dev.Tracer) -> None
1277 Job.__init__(self)
1278 self.job_control = job_control
1279 self.job_list = job_list
1280 self.tracer = tracer
1281
1282 self.procs = [] # type: List[Process]
1283 self.pids = [] # type: List[int] # pids in order
1284 self.pipe_status = [] # type: List[int] # status in order
1285 self.status = -1 # for 'wait' jobs
1286
1287 self.pgid = INVALID_PGID
1288
1289 # Optional for foreground
1290 self.last_thunk = None # type: Tuple[CommandEvaluator, command_t]
1291 self.last_pipe = None # type: Tuple[int, int]
1292
1293 self.sigpipe_status_ok = sigpipe_status_ok
1294
1295 def ProcessGroupId(self):
1296 # type: () -> int
1297 """Returns the group ID of this pipeline.
1298
1299 In an interactive shell, it's often the FIRST.
1300 """
1301 return self.pgid
1302
1303 def PidForWait(self):
1304 # type: () -> int
1305 """Return the pid we can wait on."""
1306 return self.LastPid()
1307
1308 def LastPid(self):
1309 # type: () -> int
1310 """The $! variable is the PID of the LAST pipeline part.
1311
1312 But in an interactive shell, the PGID is the PID of the FIRST pipeline part.
1313
1314 It would be nicer if these were consistent!
1315 """
1316 return self.pids[-1]
1317
1318 def DisplayJob(self, job_id, f, style):
1319 # type: (int, mylib.Writer, int) -> None
1320 if style == STYLE_PID_ONLY:
1321 f.write('%d\n' % self.procs[0].pid)
1322 else:
1323 # Note: this is STYLE_LONG.
1324 for i, proc in enumerate(self.procs):
1325 if i == 0: # show job ID for first element in pipeline
1326 job_id_str = '%%%d' % job_id
1327 else:
1328 job_id_str = ' ' # 2 spaces
1329
1330 f.write('%s %d %7s ' %
1331 (job_id_str, proc.pid, _JobStateStr(proc.state)))
1332 f.write(proc.thunk.UserString())
1333 f.write('\n')
1334
1335 def DebugPrint(self):
1336 # type: () -> None
1337 print('Pipeline in state %s' % _JobStateStr(self.state))
1338 if mylib.PYTHON: # %s for Process not allowed in C++
1339 for proc in self.procs:
1340 print(' proc %s' % proc)
1341 _, last_node = self.last_thunk
1342 print(' last %s' % last_node)
1343 print(' pipe_status %s' % self.pipe_status)
1344
1345 def Add(self, p):
1346 # type: (Process) -> None
1347 """Append a process to the pipeline."""
1348 if len(self.procs) == 0:
1349 self.procs.append(p)
1350 return
1351
1352 r, w = posix.pipe()
1353 #log('pipe for %s: %d %d', p, r, w)
1354 prev = self.procs[-1]
1355
1356 prev.AddStateChange(StdoutToPipe(r, w)) # applied on StartPipeline()
1357 p.AddStateChange(StdinFromPipe(r, w)) # applied on StartPipeline()
1358
1359 p.AddPipeToClose(r, w) # MaybeClosePipe() on StartPipeline()
1360
1361 self.procs.append(p)
1362
1363 def AddLast(self, thunk):
1364 # type: (Tuple[CommandEvaluator, command_t]) -> None
1365 """Append the last noden to the pipeline.
1366
1367 This is run in the CURRENT process. It is OPTIONAL, because
1368 pipelines in the background are run uniformly.
1369 """
1370 self.last_thunk = thunk
1371
1372 assert len(self.procs) != 0
1373
1374 r, w = posix.pipe()
1375 prev = self.procs[-1]
1376 prev.AddStateChange(StdoutToPipe(r, w))
1377
1378 self.last_pipe = (r, w) # So we can connect it to last_thunk
1379
1380 def StartPipeline(self, waiter):
1381 # type: (Waiter) -> None
1382
1383 # If we are creating a pipeline in a subshell or we aren't running with job
1384 # control, our children should remain in our inherited process group.
1385 # the pipelines's group ID.
1386 if self.job_control.Enabled():
1387 self.pgid = OWN_LEADER # first process in pipeline is the leader
1388
1389 for i, proc in enumerate(self.procs):
1390 if self.pgid != INVALID_PGID:
1391 proc.AddStateChange(SetPgid(self.pgid, self.tracer))
1392
1393 # Figure out the pid
1394 pid = proc.StartProcess(trace.PipelinePart)
1395 if i == 0 and self.pgid != INVALID_PGID:
1396 # Mimic bash and use the PID of the FIRST process as the group
1397 # for the whole pipeline.
1398 self.pgid = pid
1399
1400 self.pids.append(pid)
1401 self.pipe_status.append(-1) # uninitialized
1402
1403 # NOTE: This is done in the SHELL PROCESS after every fork() call.
1404 # It can't be done at the end; otherwise processes will have descriptors
1405 # from non-adjacent pipes.
1406 proc.MaybeClosePipe()
1407
1408 if self.last_thunk:
1409 self.pipe_status.append(-1) # for self.last_thunk
1410
1411 #log('Started pipeline PIDS=%s, pgid=%d', self.pids, self.pgid)
1412
1413 def Wait(self, waiter):
1414 # type: (Waiter) -> List[int]
1415 """Wait for this Pipeline to finish."""
1416
1417 assert self.procs, "no procs for Wait()"
1418 # waitpid(-1) zero or more times
1419 while self.state == job_state_e.Running:
1420 # Keep waiting until there's nothing to wait for.
1421 result, _ = waiter.WaitForOne()
1422 if result == W1_NO_CHILDREN:
1423 break
1424
1425 return self.pipe_status
1426
1427 def JobWait(self, waiter):
1428 # type: (Waiter) -> wait_status_t
1429 """Pipeline::JobWait(), called by 'wait' builtin, e.g. 'wait %1'."""
1430 # wait builtin can be interrupted
1431 assert self.procs, "no procs for Wait()"
1432 while self.state == job_state_e.Running:
1433 result, w1_arg = waiter.WaitForOne()
1434
1435 if result == W1_CALL_INTR: # signal
1436 return wait_status.Cancelled(w1_arg)
1437
1438 if result == W1_NO_CHILDREN:
1439 break
1440
1441 # Ignore W1_EXITED, W1_STOPPED - these are OTHER processes
1442
1443 assert all(st >= 0 for st in self.pipe_status), self.pipe_status
1444 return wait_status.Pipeline(self.state, self.pipe_status)
1445
1446 #for pid in self.pids: # Clean up to avoid leaks
1447 # self.job_list.PopChildProcess(pid)
1448
1449 def RunLastPart(self, waiter, fd_state):
1450 # type: (Waiter, FdState) -> List[int]
1451 """Run this pipeline synchronously (foreground pipeline).
1452
1453 Returns:
1454 pipe_status (list of integers).
1455 """
1456 assert len(self.pids) == len(self.procs)
1457
1458 # TODO: break circular dep. Bit flags could go in ASDL or headers.
1459 from osh import cmd_eval
1460
1461 # This is tcsetpgrp()
1462 # TODO: fix race condition -- I believe the first process could have
1463 # stopped already, and thus getpgid() will fail
1464 self.job_control.MaybeGiveTerminal(self.pgid)
1465
1466 # Run the last part of the pipeline IN PARALLEL with other processes. It
1467 # may or may not fork:
1468 # echo foo | read line # no fork, the builtin runs in THIS shell process
1469 # ls | wc -l # fork for 'wc'
1470
1471 cmd_ev, last_node = self.last_thunk
1472
1473 assert self.last_pipe is not None
1474 r, w = self.last_pipe # set in AddLast()
1475 posix.close(w) # we will not write here
1476
1477 # Fix lastpipe / job control / DEBUG trap interaction
1478 cmd_flags = cmd_eval.NoDebugTrap if self.job_control.Enabled() else 0
1479
1480 # The ERR trap only runs for the WHOLE pipeline, not the COMPONENTS in
1481 # a pipeline.
1482 cmd_flags |= cmd_eval.NoErrTrap
1483
1484 io_errors = [] # type: List[error.IOError_OSError]
1485 with ctx_Pipe(fd_state, r, io_errors):
1486 cmd_ev.ExecuteAndCatch(last_node, cmd_flags)
1487
1488 if len(io_errors):
1489 e_die('Error setting up last part of pipeline: %s' %
1490 pyutil.strerror(io_errors[0]))
1491
1492 # We won't read anymore. If we don't do this, then 'cat' in 'cat
1493 # /dev/urandom | sleep 1' will never get SIGPIPE.
1494 posix.close(r)
1495
1496 self.pipe_status[-1] = cmd_ev.LastStatus()
1497 if self.AllExited():
1498 self.state = job_state_e.Exited
1499
1500 #log('pipestatus before all have finished = %s', self.pipe_status)
1501 return self.Wait(waiter)
1502
1503 def AllExited(self):
1504 # type: () -> bool
1505
1506 # mycpp rewrite: all(status != -1 for status in self.pipe_status)
1507 for status in self.pipe_status:
1508 if status == -1:
1509 return False
1510 return True
1511
1512 def WhenPartExited(self, pid, status):
1513 # type: (int, int) -> None
1514 """Called by Process::WhenExited()"""
1515 #log('Pipeline WhenExited %d %d', pid, status)
1516 i = self.pids.index(pid)
1517 assert i != -1, 'Unexpected PID %d' % pid
1518
1519 if status == 141 and self.sigpipe_status_ok:
1520 status = 0
1521
1522 self.pipe_status[i] = status
1523 if self.AllExited():
1524 if self.job_id != -1:
1525 # Job might have been brought to the foreground after being
1526 # assigned a job ID.
1527 if self.in_background:
1528 print_stderr('[%%%d] PGID %d Done' %
1529 (self.job_id, self.pids[0]))
1530
1531 # status of pipeline is status of last process
1532 self.status = self.pipe_status[-1]
1533 self.state = job_state_e.Exited
1534 if not self.in_background:
1535 self.job_control.MaybeTakeTerminal()
1536
1537
1538def _JobStateStr(i):
1539 # type: (job_state_t) -> str
1540 return job_state_str(i)[10:] # remove 'job_state.'
1541
1542
1543def _GetTtyFd():
1544 # type: () -> int
1545 """Returns -1 if stdio is not a TTY."""
1546 try:
1547 return posix.open("/dev/tty", O_NONBLOCK | O_NOCTTY | O_RDWR, 0o666)
1548 except (IOError, OSError) as e:
1549 return -1
1550
1551
1552class ctx_TerminalControl(object):
1553
1554 def __init__(self, job_control, errfmt):
1555 # type: (JobControl, ui.ErrorFormatter) -> None
1556 job_control.InitJobControl()
1557 self.job_control = job_control
1558 self.errfmt = errfmt
1559
1560 def __enter__(self):
1561 # type: () -> None
1562 pass
1563
1564 def __exit__(self, type, value, traceback):
1565 # type: (Any, Any, Any) -> None
1566
1567 # Return the TTY to the original owner before exiting.
1568 try:
1569 self.job_control.MaybeReturnTerminal()
1570 except error.FatalRuntime as e:
1571 # Don't abort the shell on error, just print a message.
1572 self.errfmt.PrettyPrintError(e)
1573
1574
1575class JobControl(object):
1576 """Interface to setpgid(), tcsetpgrp(), etc."""
1577
1578 def __init__(self):
1579 # type: () -> None
1580
1581 # The main shell's PID and group ID.
1582 self.shell_pid = -1
1583 self.shell_pgid = -1
1584
1585 # The fd of the controlling tty. Set to -1 when job control is disabled.
1586 self.shell_tty_fd = -1
1587
1588 # For giving the terminal back to our parent before exiting (if not a login
1589 # shell).
1590 self.original_tty_pgid = -1
1591
1592 def InitJobControl(self):
1593 # type: () -> None
1594 self.shell_pid = posix.getpid()
1595 orig_shell_pgid = posix.getpgid(0)
1596 self.shell_pgid = orig_shell_pgid
1597 self.shell_tty_fd = _GetTtyFd()
1598
1599 # If we aren't the leader of our process group, create a group and mark
1600 # ourselves as the leader.
1601 if self.shell_pgid != self.shell_pid:
1602 try:
1603 posix.setpgid(self.shell_pid, self.shell_pid)
1604 self.shell_pgid = self.shell_pid
1605 except (IOError, OSError) as e:
1606 self.shell_tty_fd = -1
1607
1608 if self.shell_tty_fd != -1:
1609 self.original_tty_pgid = posix.tcgetpgrp(self.shell_tty_fd)
1610
1611 # If stdio is a TTY, put the shell's process group in the foreground.
1612 try:
1613 posix.tcsetpgrp(self.shell_tty_fd, self.shell_pgid)
1614 except (IOError, OSError) as e:
1615 # We probably aren't in the session leader's process group. Disable job
1616 # control.
1617 self.shell_tty_fd = -1
1618 self.shell_pgid = orig_shell_pgid
1619 posix.setpgid(self.shell_pid, self.shell_pgid)
1620
1621 def Enabled(self):
1622 # type: () -> bool
1623 """
1624 Only the main shell process should bother with job control functions.
1625 """
1626 #log('ENABLED? %d', self.shell_tty_fd)
1627
1628 # TODO: get rid of getpid()? I think SubProgramThunk should set a
1629 # flag.
1630 return self.shell_tty_fd != -1 and posix.getpid() == self.shell_pid
1631
1632 # TODO: This isn't a PID. This is a process group ID?
1633 #
1634 # What should the table look like?
1635 #
1636 # Do we need the last PID? I don't know why bash prints that. Probably so
1637 # you can do wait $!
1638 # wait -n waits for any node to go from job_state_e.Running to job_state_e.Done?
1639 #
1640 # And it needs a flag for CURRENT, for the implicit arg to 'fg'.
1641 # job_id is just an integer. This is sort of lame.
1642 #
1643 # [job_id, flag, pgid, job_state, node]
1644
1645 def MaybeGiveTerminal(self, pgid):
1646 # type: (int) -> None
1647 """If stdio is a TTY, move the given process group to the
1648 foreground."""
1649 if not self.Enabled():
1650 # Only call tcsetpgrp when job control is enabled.
1651 return
1652
1653 try:
1654 posix.tcsetpgrp(self.shell_tty_fd, pgid)
1655 except (IOError, OSError) as e:
1656 e_die('osh: Failed to move process group %d to foreground: %s' %
1657 (pgid, pyutil.strerror(e)))
1658
1659 def MaybeTakeTerminal(self):
1660 # type: () -> None
1661 """If stdio is a TTY, return the main shell's process group to the
1662 foreground."""
1663 self.MaybeGiveTerminal(self.shell_pgid)
1664
1665 def MaybeReturnTerminal(self):
1666 # type: () -> None
1667 """Called before the shell exits."""
1668 self.MaybeGiveTerminal(self.original_tty_pgid)
1669
1670
1671class JobList(object):
1672 """Global list of jobs, used by a few builtins."""
1673
1674 def __init__(self):
1675 # type: () -> None
1676
1677 # self.child_procs is used by WaitForOne() to call proc.WhenExited()
1678 # and proc.WhenStopped().
1679 self.child_procs = {} # type: Dict[int, Process]
1680
1681 # self.jobs is used by 'wait %1' and 'fg %2'
1682 # job_id -> Job
1683 self.jobs = {} # type: Dict[int, Job]
1684
1685 # self.pid_to_job is used by 'wait -n' and 'wait' - to call
1686 # CleanupWhenProcessExits(). They Dict key is job.PidForWait()
1687 self.pid_to_job = {} # type: Dict[int, Job]
1688
1689 self.debug_pipelines = [] # type: List[Pipeline]
1690
1691 # Counter used to assign IDs to jobs. It is incremented every time a job
1692 # is created. Once all active jobs are done it is reset to 1. I'm not
1693 # sure if this reset behavior is mandated by POSIX, but other shells do
1694 # it, so we mimic for the sake of compatibility.
1695 self.next_job_id = 1
1696
1697 def AddJob(self, job):
1698 # type: (Job) -> int
1699 """Register a background job.
1700
1701 A job is either a Process or Pipeline. You can resume a job with 'fg',
1702 kill it with 'kill', etc.
1703
1704 Two cases:
1705
1706 1. async jobs: sleep 5 | sleep 4 &
1707 2. stopped jobs: sleep 5; then Ctrl-Z
1708 """
1709 job_id = self.next_job_id
1710 self.next_job_id += 1
1711
1712 # Look up the job by job ID, for wait %1, kill %1, etc.
1713 self.jobs[job_id] = job
1714
1715 # Pipelines
1716 self.pid_to_job[job.PidForWait()] = job
1717
1718 # Mutate the job itself
1719 job.job_id = job_id
1720
1721 return job_id
1722
1723 def JobFromPid(self, pid):
1724 # type: (int) -> Optional[Job]
1725 return self.pid_to_job.get(pid)
1726
1727 def _MaybeResetCounter(self):
1728 # type: () -> None
1729 if len(self.jobs) == 0:
1730 self.next_job_id = 1
1731
1732 def CleanupWhenJobExits(self, job):
1733 # type: (Job) -> None
1734 """Called when say 'fg %2' exits, and when 'wait %2' exits"""
1735 mylib.dict_erase(self.jobs, job.job_id)
1736
1737 mylib.dict_erase(self.pid_to_job, job.PidForWait())
1738
1739 self._MaybeResetCounter()
1740
1741 def CleanupWhenProcessExits(self, pid):
1742 # type: (int) -> None
1743 """Given a PID, remove the job if it has Exited."""
1744
1745 job = self.pid_to_job.get(pid)
1746 if job and job.state == job_state_e.Exited:
1747 # Note: only the LAST PID in a pipeline will ever be here, but it's
1748 # OK to try to delete it.
1749 mylib.dict_erase(self.pid_to_job, pid)
1750
1751 mylib.dict_erase(self.jobs, job.job_id)
1752
1753 self._MaybeResetCounter()
1754
1755 def AddChildProcess(self, pid, proc):
1756 # type: (int, Process) -> None
1757 """Every child process should be added here as soon as we know its PID.
1758
1759 When the Waiter gets an EXITED or STOPPED notification, we need
1760 to know about it so 'jobs' can work.
1761
1762 Note: this contains Process objects that are part of a Pipeline object.
1763 Does it need to?
1764 """
1765 self.child_procs[pid] = proc
1766
1767 def PopChildProcess(self, pid):
1768 # type: (int) -> Optional[Process]
1769 """Remove the child process with the given PID."""
1770 pr = self.child_procs.get(pid)
1771 if pr is not None:
1772 mylib.dict_erase(self.child_procs, pid)
1773 return pr
1774
1775 if mylib.PYTHON:
1776
1777 def AddPipeline(self, pi):
1778 # type: (Pipeline) -> None
1779 """For debugging only."""
1780 self.debug_pipelines.append(pi)
1781
1782 def GetCurrentAndPreviousJobs(self):
1783 # type: () -> Tuple[Optional[Job], Optional[Job]]
1784 """Return the "current" and "previous" jobs (AKA `%+` and `%-`).
1785
1786 See the POSIX specification for the `jobs` builtin for details:
1787 https://pubs.opengroup.org/onlinepubs/007904875/utilities/jobs.html
1788
1789 IMPORTANT NOTE: This method assumes that the jobs list will not change
1790 during its execution! This assumption holds for now because we only ever
1791 update the jobs list from the main loop after WaitPid() informs us of a
1792 change. If we implement `set -b` and install a signal handler for
1793 SIGCHLD we should be careful to synchronize it with this function. The
1794 unsafety of mutating GC data structures from a signal handler should
1795 make this a non-issue, but if bugs related to this appear this note may
1796 be helpful...
1797 """
1798 # Split all active jobs by state and sort each group by decreasing job
1799 # ID to approximate newness.
1800 stopped_jobs = [] # type: List[Job]
1801 running_jobs = [] # type: List[Job]
1802 for i in xrange(0, self.next_job_id):
1803 job = self.jobs.get(i, None)
1804 if not job:
1805 continue
1806
1807 if job.state == job_state_e.Stopped:
1808 stopped_jobs.append(job)
1809
1810 elif job.state == job_state_e.Running:
1811 running_jobs.append(job)
1812
1813 current = None # type: Optional[Job]
1814 previous = None # type: Optional[Job]
1815 # POSIX says: If there is any suspended job, then the current job shall
1816 # be a suspended job. If there are at least two suspended jobs, then the
1817 # previous job also shall be a suspended job.
1818 #
1819 # So, we will only return running jobs from here if there are no recent
1820 # stopped jobs.
1821 if len(stopped_jobs) > 0:
1822 current = stopped_jobs.pop()
1823
1824 if len(stopped_jobs) > 0:
1825 previous = stopped_jobs.pop()
1826
1827 if len(running_jobs) > 0 and not current:
1828 current = running_jobs.pop()
1829
1830 if len(running_jobs) > 0 and not previous:
1831 previous = running_jobs.pop()
1832
1833 if not previous:
1834 previous = current
1835
1836 return current, previous
1837
1838 def GetJobWithSpec(self, job_spec):
1839 # type: (str) -> Optional[Job]
1840 """Parse the given job spec and return the matching job. If there is no
1841 matching job, this function returns None.
1842
1843 See the POSIX spec for the `jobs` builtin for details about job specs:
1844 https://pubs.opengroup.org/onlinepubs/007904875/utilities/jobs.html
1845 """
1846 if job_spec in CURRENT_JOB_SPECS:
1847 current, _ = self.GetCurrentAndPreviousJobs()
1848 return current
1849
1850 if job_spec == '%-':
1851 _, previous = self.GetCurrentAndPreviousJobs()
1852 return previous
1853
1854 #log('** SEARCHING %s', self.jobs)
1855 # TODO: Add support for job specs based on prefixes of process argv.
1856 m = util.RegexSearch(r'^%([0-9]+)$', job_spec)
1857 if m is not None:
1858 assert len(m) == 2
1859 job_id = int(m[1])
1860 if job_id in self.jobs:
1861 return self.jobs[job_id]
1862
1863 return None
1864
1865 def DisplayJobs(self, style):
1866 # type: (int) -> None
1867 """Used by the 'jobs' builtin.
1868
1869 https://pubs.opengroup.org/onlinepubs/9699919799/utilities/jobs.html
1870
1871 "By default, the jobs utility shall display the status of all stopped jobs,
1872 running background jobs and all jobs whose status has changed and have not
1873 been reported by the shell."
1874 """
1875 # NOTE: A job is a background process or pipeline.
1876 #
1877 # echo hi | wc -l -- this starts two processes. Wait for TWO
1878 # echo hi | wc -l & -- this starts a process which starts two processes
1879 # Wait for ONE.
1880 #
1881 # 'jobs -l' GROUPS the PIDs by job. It has the job number, + - indicators
1882 # for %% and %-, PID, status, and "command".
1883 #
1884 # Every component of a pipeline is on the same line with 'jobs', but
1885 # they're separated into different lines with 'jobs -l'.
1886 #
1887 # See demo/jobs-builtin.sh
1888
1889 # $ jobs -l
1890 # [1]+ 24414 Stopped sleep 5
1891 # 24415 | sleep 5
1892 # [2] 24502 Running sleep 6
1893 # 24503 | sleep 6
1894 # 24504 | sleep 5 &
1895 # [3]- 24508 Running sleep 6
1896 # 24509 | sleep 6
1897 # 24510 | sleep 5 &
1898
1899 f = mylib.Stdout()
1900 for job_id, job in iteritems(self.jobs):
1901 # Use the %1 syntax
1902 job.DisplayJob(job_id, f, style)
1903
1904 def DebugPrint(self):
1905 # type: () -> None
1906
1907 f = mylib.Stdout()
1908 f.write('\n')
1909 f.write('[process debug info]\n')
1910
1911 for pid, proc in iteritems(self.child_procs):
1912 proc.DisplayJob(-1, f, STYLE_DEFAULT)
1913 #p = ' |' if proc.parent_pipeline else ''
1914 #print('%d %7s %s%s' % (pid, _JobStateStr(proc.state), proc.thunk.UserString(), p))
1915
1916 if len(self.debug_pipelines):
1917 f.write('\n')
1918 f.write('[pipeline debug info]\n')
1919 for pi in self.debug_pipelines:
1920 pi.DebugPrint()
1921
1922 def ListRecent(self):
1923 # type: () -> None
1924 """For jobs -n, which I think is also used in the interactive
1925 prompt."""
1926 pass
1927
1928 def NumRunning(self):
1929 # type: () -> int
1930 """Return the number of running jobs.
1931
1932 Used by 'wait' and 'wait -n'.
1933 """
1934 count = 0
1935 for _, job in iteritems(self.jobs): # mycpp rewrite: from itervalues()
1936 if job.State() == job_state_e.Running:
1937 count += 1
1938 return count
1939
1940
1941# Some WaitForOne() return values, which are negative. The numbers are
1942# arbitrary negative numbers.
1943#
1944# They don't overlap with iolib.UNTRAPPED_SIGWINCH == -10
1945# which LastSignal() can return
1946
1947W1_EXITED = -11 # process exited
1948W1_STOPPED = -12 # process was stopped
1949W1_CALL_INTR = -15 # the waitpid(-1) call was interrupted
1950
1951W1_NO_CHILDREN = -13 # no child processes to wait for
1952W1_NO_CHANGE = -14 # WNOHANG was passed and there were no state changes
1953
1954NO_ARG = -20
1955
1956
1957class Waiter(object):
1958 """A capability to wait for processes.
1959
1960 This must be a singleton (and is because CommandEvaluator is a singleton).
1961
1962 Invariants:
1963 - Every child process is registered once
1964 - Every child process is waited for
1965
1966 Canonical example of why we need a GLOBAL waiter:
1967
1968 { sleep 3; echo 'done 3'; } &
1969 { sleep 4; echo 'done 4'; } &
1970
1971 # ... do arbitrary stuff ...
1972
1973 { sleep 1; exit 1; } | { sleep 2; exit 2; }
1974
1975 Now when you do wait() after starting the pipeline, you might get a pipeline
1976 process OR a background process! So you have to distinguish between them.
1977 """
1978
1979 def __init__(self, job_list, exec_opts, signal_safe, tracer):
1980 # type: (JobList, optview.Exec, iolib.SignalSafe, dev.Tracer) -> None
1981 self.job_list = job_list
1982 self.exec_opts = exec_opts
1983 self.signal_safe = signal_safe
1984 self.tracer = tracer
1985 self.last_status = 127 # wait -n error code
1986
1987 def LastStatusCode(self):
1988 # type: () -> int
1989 """Returns exit code for wait -n"""
1990 return self.last_status
1991
1992 def WaitForOne(self, waitpid_options=0):
1993 # type: (int) -> Tuple[int, int]
1994 """Wait until the next process returns (or maybe Ctrl-C).
1995
1996 Returns:
1997 One of these negative numbers:
1998 W1_NO_CHILDREN Nothing to wait for
1999 W1_NO_CHANGE no state changes when WNOHANG passed - used by
2000 main loop
2001 W1_EXITED Process exited (with or without signal)
2002 W1_STOPPED Process stopped
2003 W1_CALL_INTR
2004 UNTRAPPED_SIGWINCH
2005 Or
2006 result > 0 Signal that waitpid() was interrupted with
2007
2008 In the interactive shell, we return 0 if we get a Ctrl-C, so the caller
2009 will try again.
2010
2011 Callers:
2012 wait -n -- loop until there is one fewer process (TODO)
2013 wait -- loop until there are no processes
2014 wait $! -- loop until job state is Done (process or pipeline)
2015 Process::Wait() -- loop until Process state is done
2016 Pipeline::Wait() -- loop until Pipeline state is done
2017
2018 Comparisons:
2019 bash: jobs.c waitchld() Has a special case macro(!) CHECK_WAIT_INTR for
2020 the wait builtin
2021
2022 dash: jobs.c waitproc() uses sigfillset(), sigprocmask(), etc. Runs in a
2023 loop while (gotsigchld), but that might be a hack for System V!
2024
2025 Should we have a cleaner API like posix::wait_for_one() ?
2026
2027 wait_result =
2028 NoChildren -- ECHILD - no more
2029 | Exited(int pid) -- process done - call job_list.PopStatus() for status
2030 # do we also we want ExitedWithSignal() ?
2031 | Stopped(int pid)
2032 | Interrupted(int sig_num) -- may or may not retry
2033 | UntrappedSigwinch -- ignored
2034
2035 | NoChange -- for WNOHANG - is this a different API?
2036 """
2037 pid, status = pyos.WaitPid(waitpid_options)
2038 if pid == 0:
2039 return W1_NO_CHANGE, NO_ARG # WNOHANG passed, and no state changes
2040
2041 if pid < 0: # error case
2042 err_num = status
2043 #log('waitpid() error => %d %s', e.errno, pyutil.strerror(e))
2044 if err_num == ECHILD:
2045 return W1_NO_CHILDREN, NO_ARG
2046
2047 if err_num == EINTR: # Bug #858 fix
2048 # e.g. 1 for SIGHUP, or also be UNTRAPPED_SIGWINCH == -1
2049 last_sig = self.signal_safe.LastSignal()
2050 if last_sig == iolib.UNTRAPPED_SIGWINCH:
2051 return iolib.UNTRAPPED_SIGWINCH, NO_ARG
2052 else:
2053 return W1_CALL_INTR, last_sig
2054
2055 # No other errors? Man page says waitpid(INT_MIN) == ESRCH, "no
2056 # such process", an invalid PID
2057 raise AssertionError()
2058
2059 # All child processes are supposed to be in this dict. Even if a
2060 # grandchild outlives the child (its parent), the shell does NOT become
2061 # the parent. The init process does.
2062 proc = self.job_list.child_procs.get(pid)
2063
2064 # TODO: hide this behind shopt --set verbose_jobs or xtrace?
2065 if proc is None:
2066 print_stderr("oils: PID %d exited, but oils didn't start it" % pid)
2067
2068 if 0:
2069 self.job_list.DebugPrint()
2070
2071 was_stopped = False
2072 if WIFSIGNALED(status):
2073 term_sig = WTERMSIG(status)
2074 status = 128 + term_sig
2075
2076 # Print newline after Ctrl-C.
2077 if term_sig == SIGINT:
2078 print('')
2079
2080 if proc:
2081 proc.WhenExited(pid, status)
2082
2083 elif WIFEXITED(status):
2084 status = WEXITSTATUS(status)
2085 if proc:
2086 proc.WhenExited(pid, status)
2087
2088 elif WIFSTOPPED(status):
2089 was_stopped = True
2090
2091 stop_sig = WSTOPSIG(status)
2092
2093 # TODO: only print this interactively
2094 print_stderr('')
2095 print_stderr('oils: PID %d Stopped with signal %d' %
2096 (pid, stop_sig))
2097 if proc:
2098 proc.WhenStopped(stop_sig)
2099
2100 else:
2101 raise AssertionError(status)
2102
2103 self.last_status = status # for wait -n
2104 self.tracer.OnProcessEnd(pid, status)
2105
2106 if was_stopped:
2107 return W1_STOPPED, pid
2108 else:
2109 return W1_EXITED, pid
2110
2111 def PollForEvents(self):
2112 # type: () -> None
2113 """For the interactive shell to print when processes have exited."""
2114 while True:
2115 result, _ = self.WaitForOne(waitpid_options=WNOHANG)
2116
2117 if result == W1_NO_CHANGE:
2118 break
2119 if result == W1_NO_CHILDREN:
2120 break
2121
2122 # Keep polling here
2123 assert result in (W1_EXITED, W1_STOPPED), result
2124 # W1_CALL_INTR and iolib.UNTRAPPED_SIGWINCH should not happen,
2125 # because WNOHANG is a non-blocking call