[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: recognizing an xterm running only bash from the CLI



On Mon, Aug 11, 2025 at 7:15 AM Mike McClain <mike.junk.46@att.net> wrote:
> On Sun, Aug 10, 2025 at 11:28:08PM -0400, Greg Wooledge wrote:
> Sorry I wasn't clear, I'll try again.
> I've defined to9 () { echo "$1" > /dev/tty9 } to be used from an xterm.
> I'd like to have a similar function toX() to be used on a virtual
> terminal that would print some text on the xterm running only bash

How exactly do you define "only running bash"?
That that's the only PID with that xterm as controlling tty?
That bash is the only child PID of the xterm PID?
That the only descendent PIDs of the xterm PID is single PID that's
running bash?
You can use fuser(1) to identify the PIDs of the xterms running under
one's ID (or all if
run as root).
Can use ps(1) or pstree(1) or the like, to identify descendent PIDs.
Can use the proc filesystem to find tty(s), if any, associated with
the bash PID,
but those may or may not be the tty allocated to the xterm (e.g. could
be redirected).
So, e.g.:
$ ps lwwwwp $({ fuser /usr/bin/xterm 2>>/dev/null; echo; } | sed -e
's/^ *//;s/  */,/g;')
F   UID   PID  PPID PRI  NI    VSZ   RSS WCHAN  STAT TTY        TIME COMMAND
0  1003 13764 14462  20   0  12928  7632 do_sel S    pts/0      0:00 xterm
0  1003 14452 14420  20   0  14604  6080 do_sel S    tty5       0:02
xterm -ls -geometry +0+0 -n login -display :0
$ pstree -alp 13764 | wc -l
2
$ pstree -alp 14452 | wc -l
341
$ pstree -alp 13764
xterm,13764
  `-bash,13768
$
$ readlink /proc/13768/exe
/usr/bin/bash
$ readlink /proc/13768/fd/* | sort -u | grep '^/dev/pts/[0-9]\{1,\}$'
/dev/pts/20
$
So, then you've identified the xterm and bash PIDs matching your criteria,
and have a probable tty device that's assigned to that xterm session.
But not guaranteed that's the tty assigned to xterm.
E.g. if in that bash shell, I do:
$ exec dash
$ exec 0</dev/tty 1>/dev/tty 2>&1
$ exec bash
$
If we check again, still meets same criteria, but for tty, we see /dev/tty
(the "magic" tty, that always refers to the current controlling
terminal - if any)
$ readlink /proc/13768/fd/* | sort -u
/dev/tty
$ readlink /proc/13768/exe
/usr/bin/bash
$
We can however, find what /dev/tty is for that PID, via ps:
$ ps lwwwwp 13768
F   UID   PID  PPID PRI  NI    VSZ   RSS WCHAN  STAT TTY        TIME COMMAND
0  1003 13768 13764  20   0   4192  3328 do_sel Ss+  pts/20     0:00 bash
$
But that still won't work in all circumstances.


Reply to: