Created
April 1, 2021 02:56
-
-
Save mwhudson/821c22f27d228e7f4f9fdd9c1abb4037 to your computer and use it in GitHub Desktop.
the unix end boss is hard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import pty | |
import signal | |
import sys | |
import subprocess | |
import time | |
def am_i_foreground(): | |
if os.tcgetpgrp(0) == os.getpgrp(): | |
return 'foreground' | |
else: | |
return 'background' | |
master, slave = pty.openpty() | |
p = subprocess.Popen(['sh'], stdin=slave, stdout=slave, stderr=slave) | |
print('subshell started', am_i_foreground()) | |
time.sleep(0.1) | |
print('subshell running', am_i_foreground()) | |
if '-k' in sys.argv[1:]: | |
os.kill(p.pid, signal.SIGKILL) | |
else: | |
os.close(master) | |
p.wait() | |
print('subshell exited status', p.returncode, am_i_foreground()) | |
time.sleep(1.0) | |
print('after waiting', am_i_foreground()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mwhudson@anduril:~/src$ python3 pgrpfun.py | |
subshell started foreground | |
subshell running background | |
subshell exited status 0 foreground | |
after waiting foreground | |
mwhudson@anduril:~/src$ python3 pgrpfun.py -k | |
subshell started foreground | |
subshell running background | |
subshell exited status -9 background | |
after waiting background |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment