[Gllug] Re-access broken remote connection to process?

Robert McKay robert at mckay.com
Mon Jun 21 10:15:18 UTC 2010


On Tue, Jun 15, 2010 at 8:08 PM, gvim <gvimrc at gmail.com> wrote:

> Supposing I'm connected remotely to a server process via SSH and I lose
> that connection. The process is still running and it's ID is available via
> top or ps but can I get its output back into a tty? If so, how?
>

You can attach to the process with a debugger, open a new tty and then dup
stdin/stdout/stderr to the new tty. I once wrote a shell script to automate
this process. It does work - however not always for various reasons.

note: it needs /dev/ttypX /dev/ptypX devices so if you don't have those
(modern linux distributions tend to only come with /dev/pmtx) you'll need to
create one first using:

mknod /dev/ptyp1 c 2 1
mknod /dev/ttyp1 c 3 1

Once that's done, connect a terminal program (minicom or similar) to
/dev/ptyp1 and run this script. The process should appear inside minicom
under control of the new pseudo tty.

Rob

#!/bin/bash
#
# hijack.sh - A script for migrating a process from one terminal to another.
#             by Robert McKay <robert at mckay.com>
#
#
# Start a terminal program on /dev/ptyp1. This must be done first.
# Locate the pid of the process you are trying to gank
#
# Take a deep breath...
#
# Then run:
# ./this.sh <pid>
#
# You should now have a new fork() of the original program (inc. state and
# open fd's) under the control of your terminal program. The original (parent)
# side of the fork should have exit'd. It's like using 'screen' except you
# don't have to think of it in advance.
#

pid=$1
(
  echo 'set follow-fork-mode child'
  echo 'call signal(1, 1)' # block HUP signal from the disconnecting terminal
  echo 'call raise(17)' # not sure if this really helps
  echo 'call fork()'
  echo 'call kill('$pid', 9)'
  sleep 1
  echo 'call setsid()'
  echo 'call close(0)'
  echo 'call open("/dev/ttyp1", 66, 0666)'
  echo 'call dup2(0, 1)'
  echo 'call dup2(0, 2)'
  echo 'call dup2(0, 4)'
  echo 'call dup2(0, 5)'
  echo 'call dup2(0, 6)'
  echo 'call ioctl(0, 21518, 0)' # set new controlling terminal
  echo 'call signal(1, $1)' # replace signal handler
  echo 'detach'
  sleep 3
) | gdb -q -p $pid -x -
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.lug.org.uk/pipermail/gllug/attachments/20100621/6e6cd90a/attachment.html>
-------------- next part --------------
-- 
Gllug mailing list  -  Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug


More information about the GLLUG mailing list