-
-
Save Oyonax/1a48a66611f60fac36f01632461cd5fa to your computer and use it in GitHub Desktop.
Script to switch console attached to a command (for Linux)
This file contains hidden or 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
| #!/bin/bash | |
| # For example: switch-tty.sh `pidof vi` `tty` | |
| target=$1 | |
| dest=$2 | |
| if [ -z "$target" -o -z "$dest" ]; then | |
| echo "usage: $0 pid target" | |
| exit 1 | |
| fi | |
| current="$(readlink /proc/$target/fd/0)" | |
| echo "Current stdin: $current" | |
| if [ "$current" = "$dest" ]; then | |
| echo "no switch is required." | |
| exit 1 | |
| fi | |
| tty>/dev/null < "$current" && srctty=1 | |
| tty>/dev/null < "$dest" && desttty=1 | |
| tty>/dev/null && istty=1 | |
| [ -n "$istty" -a "$(tty)" = "$dest" ] && thistty=1 | |
| fds=() | |
| for x in /proc/$target/fd/*; do | |
| if [ "$current" = "$(readlink $x)" ]; then | |
| fd=${x##*/} | |
| fds=(${fds[@]} $fd) | |
| fi | |
| done | |
| echo "Target fds: ${fds[@]}" | |
| leader=$( ps a | grep "${dest#/dev/}" | setsid grep Ss | cut -f 1 -d \ ) | |
| echo "session leader: $leader" | |
| [ -n "$thistty" ] && echo "Switching to this TTY" | |
| echo -n "Continue? (y/N) " | |
| read | |
| [ "$REPLY" != "y" -a "$REPLY" != "Y" ] && exit 2 | |
| ( echo "p open(\"$dest\", 2)"; for x in ${fds[@]}; do echo "p dup2(\$1, $x)"; done; echo "p close(\$1)"; echo "detach"; echo "quit" ) | gdb -p $target | |
| if [ -n "$srctty" -a -n "$desttty" ]; then | |
| stty -F $dest "$( stty -g -F "$current" )" | |
| [ -n "$thistty" ] && clear | |
| kill -STOP $leader | |
| kill -STOP $target | |
| sleep 1 | |
| kill -CONT $target | |
| kill -WINCH $target | |
| fi | |
| [ -n "$thistty" ] && while :; do sleep 60; kill -0 $target || break; done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment