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

Users browsing this thread: 1 Guest(s)
Long time nixers
This is question that came up in a german board:

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". 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:


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

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

    case $comm in
            echo Looks like I\'m running via SSH, PID $pid, "'$comm'"
            echo Looks like I\'m running on a Linux VT, PID $pid, "'$comm'"

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

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

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 vain - 02-07-2016, 02:23 PM