Skip to content

Instantly share code, notes, and snippets.

@4z3
Created June 18, 2011 14:16
Show Gist options
  • Save 4z3/1033129 to your computer and use it in GitHub Desktop.
Save 4z3/1033129 to your computer and use it in GitHub Desktop.
Fix TTY job-control
#? /bin/sh
#
# Fix TTY job-control
#
# source: Internet
#
# Let's try this:
exec </dev/tty1 >/dev/tty1 2>&1
# No, doesn't work: even if opening /dev/tty1 gave sh the ctty,
# sh wouldn't know it - it checks for ctty just once at startup.
# Let's try re-execing sh:
exec </dev/tty1 >/dev/tty1 2>&1
exec sh
# Got "sh: can't access tty" again. Why?
# The reason is somewhat obscure: kernel starts process with PID=1
# (in this case, shell) with SID=0 and PGID=0, not with SID=1 and PGID=1
# as you'd expect. IOW: our sh is not a session leader, and therefore
# cannot acquire ctty by opening /dev/tty1 (or any other tty).
# Let's try making us a session leader:
exec setsid sh
exec </dev/tty1 >/dev/tty1 2>&1
exec sh
# Yes, this worked!
# This can be combined into one command,
# but need to be careful and perform these operations
# in the correct order:
# 1. make ourself session leader,
# 2. open /dev/tty1 and thus acquire a ctty,
# 3. re-execute the shell, allowing it to notice that it has a ctty:
exec setsid sh -c 'exec sh </dev/tty1 >/dev/tty1 2>&1'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment