Created
April 2, 2022 12:22
-
-
Save ben-cohen/6c4929ef4f76024496c0705637b54869 to your computer and use it in GitHub Desktop.
Open a Linux pty for another process to attach to
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
#!/usr/bin/python3 | |
# | |
# idleterm.py: Open a pty so that a process from elsewhere - such as a gdb | |
# inferior - can attach to it and copy the IO between the pty and | |
# this process's stdin and stdout. | |
# | |
# This is a Python version of the idleterm program at | |
# https://stackoverflow.com/a/71314902/2319122 | |
# | |
# Ben Cohen, April 2022. | |
# | |
import pty | |
import os | |
import select | |
import sys | |
import termios | |
import threading | |
if (os.isatty(sys.stdin.fileno())): | |
attrs = termios.tcgetattr(sys.stdin) | |
attrs[3] = attrs[3] & ~(termios.ISIG | termios.ICANON | termios.ECHO) | |
termios.tcsetattr(sys.stdin, termios.TCSANOW, attrs) | |
mfd, sfd = pty.openpty() | |
print(f"pid = {os.getpid()} tty = {os.ttyname(sfd)}") | |
def do_copy(from_fd, to_fd): | |
while True: | |
rfds, wfds, xfds = select.select([from_fd], [], []) | |
if from_fd in rfds: | |
data = os.read(from_fd, 1) | |
if len(data) > 0: | |
os.write(to_fd, data) | |
t1 = threading.Thread(target=do_copy, args=(mfd, sys.stdout.fileno())) | |
t2 = threading.Thread(target=do_copy, args=(sys.stdin.fileno(), mfd)) | |
t1.start() | |
t2.start() | |
t1.join() | |
t2.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment