Хорошо, pty.fork () работает на всех платформах.
Но это не дает нам доступа к записи в TTY, как pty.openpty () slave
Чтобы обойти это, я использовал mmap
#write tty device info to memory the child and parent process can read
slaveFd, tmpfile = tempfile.mkstemp()
os.write(slaveFd, b'\x00' * mmap.PAGESIZE)
os.lseek(slaveFd, 0, os.SEEK_SET)
def getSlaves():
raw = getSlavesRaw()
returnData = []
for lessRaw in raw.strip('/').split('/'):
returnData.append("/dev/pts/" + str(lessRaw))
return returnData
def getSlavesRaw():
os.lseek(slaveFd, 0, os.SEEK_SET)
buf = mmap.mmap(slaveFd, mmap.PAGESIZE, mmap.MAP_SHARED, mmap.PROT_READ)
msg = str(buf.readline())
msg = ':'.join(msg.split(':')[:-1]).split("'")[-1]
return(msg)
def addSlave(PID):
offset = getSlavesRaw()
offset = len(offset)
os.lseek(slaveFd, offset, os.SEEK_SET)
buf = mmap.mmap(slaveFd, mmap.PAGESIZE, mmap.MAP_SHARED, mmap.PROT_WRITE)
TTY = subprocess.check_output(['ps', 'hotty', str(PID)]).strip().decode()
TTY = TTY.split("pts")[-1] + ":" # cut off pts and add a : for spacing
for index in range(offset, offset + len(TTY)):
buf[index] = ord(TTY[index - offset])
#Thanks! https://stackoverflow.com/a/52157066/5282272
# fork this script such that a child process writes to a pty that is
# controlled or "spied on" by the parent process
(child_pid, newMasterHandle) = pty.fork()
masters.append(newMasterHandle)
# A new child process has been spawned and is continuing from here.
# The original parent process is also continuing from here.
# They have "forked".
if child_pid == 0:
debug("This is the child process fork, pid %s" % os.getpid())
addSlave(os.getpid())
bashProcessList.append(subprocess.run("bash"))
else:
debug("This is the parent process fork, pid %s" % os.getpid())
debug(getSlaves())
while True:
try:
data = os.read(masters[myScreen], 1026)
except Exception:
#time.sleep(.2)
continue
yield data