ps - process hierarchy

When I started using compterm, a problem soon appeared: sometimes I forgot that compterm was loaded. So I wrote a small function to detect whether I was in a session started by compterm or just a regular zsh session.

function is_parent_compterm {
    local pid=$$
    local parent_pid

    while [ "$pid" -ne 1 ]; do
        parent_pid=$(ps -p $pid -o ppid=)
        parent_pid=${parent_pid//[[:blank:]]/}  # Remove espaços

        # Verifica se o nome do comando do processo pai é 'compterm'
        if ps -p $parent_pid -o comm= | grep -q "^compterm$"; then
            return 0  # Retorna true se encontrar 'compterm'
        fi

        pid=$parent_pid
    done

    return 1  # Retorna false se 'compterm' não for encontrado
}

This function walks through all the parent processes of the current process, and if any of them is named compterm, it returns true. With that I can customize the prompt and tell whether compterm is loaded or not.

if is_parent_compterm; then
    PS1="%F{yellow}compterm%f%F{green}>%f "
fi

The newer version of compterm doesn’t need such a complex function. When it loads, it creates an environment variable holding the process PID, so it’s easy to find out whether the shell session was started by compterm or not.

if [[ -v COMPTERM ]]; then
    PS1="%F{yellow}compterm%f%F{green}>%f "
fi

The same idea can be used in other scripts to know, for example, whether they are running under tmux or not.


Cesar Gimenes

Last modified
Tags: