Programmatically identifying PID of process running inside konsole session in active window

I’m running an interactive process in konsole (konsole -> bash -> my_program), and I’d like to have a key shortcut (e.g., Ctrl+Shift+Alt+N) in KDE that automatically runs a script, passing the PID of that process as argument to the script. Multiple konsoles may be running my_program, as different processes, so the keystroke should identify the specific process in the currently focused window, and run the script passing that PID as argument.

Note that, in konsole, all “konsoles” in all desktops are under the same PID. So the parent process for bash is the same as the parent process for another bash running in a different konsole .

I’m able to get the currently focused window using xprop , and I’m able to match it to the KDE window with dbus (it’s using in qdbus "org.kde.konsole-<PID>" /konsole/MainWindow_<ID> winId).

To inspect the process currently running, I need information under /Sessions/<ID> or under /Windows/<ID> in dbus, and I’m not able to connect the MainWindow IDs to the Window or the Session ID.

It’s like /konsole/MainWindow_<ID> has information about the actual X11/Qt/etc widget, and I can find the currently focused window that way, and /Windows/ has more abstract information and it’s corrected to sessions and processes (i.e., bash, my_program), but I can’t find the actively focused window that way.

Any ideas?

you can use the shell variable $! to get the PID of the previous command

or you can use the bash shell variable $$ to get the PID of the currently running script.

these can then be passed with the script by assigning them to a script variable or passed outside the script by writhing them to a file.

That can be configured so that each terminal has it’s own konsole process.
In Menu Settings/Configure Konsole… untick the “Run all Konsole windows in a single process” option.

From my session that has 3 konsole terminals running as an example.

$ ps afx | grep -A 1 konsole
   5424 ?        Ssl    0:02  \_ /usr/bin/konsole
   5445 pts/1    Ss+    0:00  |   \_ /bin/bash -l
   5622 ?        Ssl    0:01  \_ /usr/bin/konsole
   5647 pts/2    Ss+    0:00  |   \_ /bin/bash -l
--
   8440 ?        Ssl    0:00  \_ /usr/bin/konsole
   8464 pts/3    Ss     0:00      \_ /bin/bash -l

Oh that’s neat. Thanks!

I think this solves my problem: I can find the PID and, from its process tree, find my_program’s PID.