Skip to content

Instantly share code, notes, and snippets.

@cognitivegears
Last active July 3, 2024 02:36
Show Gist options
  • Save cognitivegears/0b6447a4c131cb5a378defcb9f755e52 to your computer and use it in GitHub Desktop.
Save cognitivegears/0b6447a4c131cb5a378defcb9f755e52 to your computer and use it in GitHub Desktop.
Function to disown and redirect output for a stopped or background process
fo() {
# Generate a random file name if no output file is provided
if [ "$#" -lt 1 ]; then
OUTPUT_FILE=$(mktemp /tmp/output_XXXXXX.log)
else
OUTPUT_FILE="$1"
fi
echo "Redirecting output to $OUTPUT_FILE"
JOB_ID=${2:-1} # Default job ID to 1 if not provided
# Check if the job exists
if ! jobs %$JOB_ID &> /dev/null; then
echo "Job ID %$JOB_ID does not exist."
return 1
fi
# Move the stopped job to the background
if ! bg %$JOB_ID &> /dev/null; then
echo "Failed to move job %$JOB_ID to the background."
return 1
fi
# Disown the job
if ! disown %$JOB_ID &> /dev/null; then
echo "Failed to disown job %$JOB_ID."
return 1
fi
# Get the PID of the job
PID=$(jobs -l %$JOB_ID | awk '{print $2}')
if [ -z "$PID" ]; then
echo "Failed to get PID for job ID %$JOB_ID."
return 1
fi
# Build the gdb commands as a string
GDB_COMMANDS=$(cat <<EOF
p (int)close(1)
p (int)open("$OUTPUT_FILE", 0101, 0666)
p (int)close(2)
p (int)dup(1)
detach
quit
EOF
)
# Check if gdb is available
if ! command -v gdb &> /dev/null; then
echo "gdb could not be found. Please install gdb to use this function."
return 1
fi
# Run gdb with process substitution
if ! echo "$GDB_COMMANDS" | gdb -p "$PID" &> /dev/null; then
echo "Failed to redirect output."
return 1
fi
echo "Output successfully redirected to $OUTPUT_FILE"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment