Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python TTY Control

I guess I'm not clear on what what the function of the getty/agetty/mgetty programs are on a linux/unix machine. I can start a shell on a tty with something like this:

TTY = '/dev/tty3'

cpid = os.fork()
if cpid == 0:
    os.closerange(0, 4)
    sys.stdin = open(TTY, 'r')
    sys.stdout = open(TTY, 'w')
    sys.stderr = open(TTY, 'w')
    os.execv(('/bin/bash',), ('bash',))

..and if i switch over to tty3, there is a shell running- but some keystrokes are ignored / are never being sent to the shell. the shell knows the TTY settings are not correct because bash will say something like 'unable to open tty, job control disabled'

I know the 'termios' module has functions to change the settings on the TTY, which is what the 'tty' module uses, but i am unable to find an example of python setting the TTY correctly and starting a shell. I feel like it should be something simple, but i don't know where to look.

looking at the source for the *etty programs didn't help me- C looks like greek to me :-/

Maybe im just not looking for the right terms? Anyone replaced the *etty programs with Python in the past and have an explanation they would care to share?

Thanks for entertaining my basic question :)

like image 239
tMC Avatar asked May 06 '11 01:05

tMC


1 Answers

I can see at least two things you're missing - there may be more:

Firstly, you need to call setsid() in the child process after closing the old standard input/standard output, and before opening the new TTY. This does two important things - it makes your new process the leader of a new session, and it disassociates it from its previous controlling terminal (merely closing that terminal is not sufficient). This will mean that when you open the new tty, it will become the controlling terminal, which is what you want.

Secondly, you need to set the TERM environment variable to match the new tty.

like image 158
caf Avatar answered Oct 20 '22 02:10

caf