Finding the terminal your script is running in - Programming On Unix

Users browsing this thread: 1 Guest(s)
movq
Long time nixers
This is question that came up in a german board: https://forum.ubuntuusers.de/topic/pruef...mein-srip/

I suspect the original author will be satisfied with a pragmatic solution. I'm forwarding the question to this forum, though, because I hope we can come up with something nice and clever. :) Just for fun.

The goal is to find the PID of the terminal your script is running in. Turns out, this is not as easy as it sounds. The naïve approach is to traverse the process tree. The parent process of your script is ... yeah, what is it? Most likely an interactive shell. But it could also be the terminal you're looking for if you started your script using something like "xterm -e foo.sh". On the other hand, if you launched the script from inside of Vim, there's an additional intermediate process.

Then there's SSH.

Then there's screen and tmux.

Then there's screen over SSH.

Then there's the Linux VT where the terminal emulator is not an actual process.

And so on. You get the idea.

That's what I got so far:

Code:
#!/bin/bash

find_parent_terminal()
{
    pid=$1
    comm=$(ps --no-headers -p $pid -o comm)

    echo Checking process $pid, "'$comm'"

    case $comm in
        sshd)
            echo Looks like I\'m running via SSH, PID $pid, "'$comm'"
            return
            ;;
        login)
            echo Looks like I\'m running on a Linux VT, PID $pid, "'$comm'"
            return
            ;;
    esac

    for fd in /proc/$pid/fd/*
    do
        if [[ "$(readlink -e -- "$fd" 2>/dev/null)" == /dev/ptmx ]]
        then
            echo Determined PID $pid as my terminal, "'$comm'"
            return
        fi
    done

    ppid=$(ps --no-headers -p $pid -o ppid)
    if (( ppid == 1 ))
    then
        echo Reached PID 1, could not find a terminal candidate
    else
        find_parent_terminal $ppid
    fi
}

find_parent_terminal $BASHPID

The idea is to traverse the process tree and look for clues. Terminal emulators usually hold an open file descriptor to /dev/ptmx, so that's what I try to find.

I used a Bash script, but any common language is fine.

Ideally, the solution runs on *BSD as well, but I'd be happy to settle for just Linux.


Messages In This Thread
Finding the terminal your script is running in - by movq - 02-07-2016, 02:23 PM