| 1 | #!/usr/bin/env python2
|
| 2 | """
|
| 3 | fork_signal_state.py
|
| 4 | """
|
| 5 | from __future__ import print_function
|
| 6 |
|
| 7 | import os
|
| 8 | import signal
|
| 9 | import sys
|
| 10 | import time
|
| 11 |
|
| 12 |
|
| 13 | def log(msg, *args):
|
| 14 | if args:
|
| 15 | msg = msg % args
|
| 16 | print(msg, file=sys.stderr)
|
| 17 |
|
| 18 |
|
| 19 | def SignalState(pid):
|
| 20 | with open('/proc/%d/status' % pid) as f:
|
| 21 | for line in f:
|
| 22 | if line.startswith('Sig'):
|
| 23 | print(line, end='')
|
| 24 |
|
| 25 |
|
| 26 | def main(argv):
|
| 27 | if 1: # ignore Ctrl-C
|
| 28 | signal.signal(signal.SIGINT, signal.SIG_IGN)
|
| 29 |
|
| 30 | parent_pid = os.getpid()
|
| 31 | log('parent is %d', parent_pid)
|
| 32 |
|
| 33 | # Hm this looks like it works
|
| 34 | # Now why doesn't Ctrl-Z through the terminal work? The process group should
|
| 35 | # be controlling the terminal
|
| 36 |
|
| 37 | # test/group-session.sh shows PGID and TPGID (controlling tty process group ID)
|
| 38 |
|
| 39 | if 0:
|
| 40 | log('===')
|
| 41 | SignalState(parent_pid)
|
| 42 | signal.signal(signal.SIGTSTP, signal.SIG_IGN)
|
| 43 | if 0:
|
| 44 | SignalState(parent_pid)
|
| 45 | log('===')
|
| 46 |
|
| 47 | line = raw_input()
|
| 48 |
|
| 49 | if line.startswith('sleep'):
|
| 50 | pid = os.fork()
|
| 51 | if pid == 0:
|
| 52 | child_pid = os.getpid()
|
| 53 |
|
| 54 | if 0:
|
| 55 | log('---')
|
| 56 | SignalState(child_pid)
|
| 57 | signal.signal(signal.SIGTSTP, signal.SIG_DFL)
|
| 58 | if 0:
|
| 59 | SignalState(child_pid)
|
| 60 | log('---')
|
| 61 |
|
| 62 | log('sleep 2 in child %d', child_pid)
|
| 63 | os.execve('/bin/sleep', ['sleep', '2'], {})
|
| 64 |
|
| 65 | elif pid < 0:
|
| 66 | raise AssertionError()
|
| 67 |
|
| 68 | else:
|
| 69 | log('parent spawned %d', pid)
|
| 70 |
|
| 71 | log('waiting')
|
| 72 | pid, status = os.waitpid(-1, os.WUNTRACED)
|
| 73 | log('wait => pid %d exited with status %d', pid, status)
|
| 74 |
|
| 75 | if os.WIFEXITED(status):
|
| 76 | log('EXITED')
|
| 77 |
|
| 78 | if os.WIFSIGNALED(status):
|
| 79 | log('SIGNALED')
|
| 80 |
|
| 81 | elif os.WIFSTOPPED(status):
|
| 82 | log('STOPPED')
|
| 83 |
|
| 84 | else:
|
| 85 | log('BAD COMMAND')
|
| 86 |
|
| 87 |
|
| 88 | if __name__ == '__main__':
|
| 89 | try:
|
| 90 | main(sys.argv)
|
| 91 | except RuntimeError as e:
|
| 92 | print('FATAL: %s' % e, file=sys.stderr)
|
| 93 | sys.exit(1)
|