nohup after the fact

The following script for Linux (change /proc/$PID/exe for other platforms) allows an already running command-line program to be put in a state as if run by nohup.

This hack can be useful when the controlling shell is not available (e.g. the X server is frozen or you can’t access the console) but you really don’t want to kill a long-running process.

#!/bin/sh
PID=$1
OUTFILE=$2
CMDFILE=`tempfile`
set -e
sed -e "s|OUTFILE|$OUTFILE|g" >$CMDFILE <<'EOF'
set $outfile=open("OUTFILE", 01101, 0600)
set $devnull=open("/dev/null", 0, 0)
print dup2($outfile,1)
print dup2($outfile,2)
print dup2($devnull,0)
print close($outfile)
print close($devnull)
print signal(1, 1)
detach
quit
EOF
gdb -q -n -batch -x $CMDFILE /proc/$PID/exe $PID > /dev/null
rm $CMDFILE