NB: For the sake of this question, please assume that the underlying OS is some flavor of Unix. If more specificity is required, then please assume that it is either Darwin or some flavor of Linux.
.emacs file, I would like to map a particular key combination only when the current
emacs process is a descendant of a
screen (GNU screen) process. I am looking for a robust way to test for this condition.
I know that
(emacs-pid) will evaluate to an integer corresponding to the pid of the current emacs process.
Beyond this point, the only thing I can come up with is the following (very fragile, IMO) monstrosity:
(if (= 0 (shell-command (format "pstree -pu $USER | grep -qP -- '-screen\\(\\d+\\)-.*-emacs\\(%d\\)'" (emacs-pid)))) (global-set-key ...) )
Basically, this code runs a
global-set-key command if the following expression evaluates to 0:
(shell-command (format "pstree -pu $USER | grep -qP -- '-screen\\(\\d+\\)-.*-emacs\\(%d\\)'" (emacs-pid)))
To evaluate this expression, Emacs will run the command below1 in a subshell, and will use its exit status as the expression's value:
pstree -pu $USER | grep -qP -- '-screen\(\d+\)-.*-emacs\(<EMACS_PID>\)'
This shell command, in turn, will have an exit status of 0 if and only if the line in the output of
pstree -pu $USER that contains the substring
-emacs(<EMACS_PID>) is preceded by a substring that matches the Perl regex
In my experience, Emacs extension code that relies on parsing the output of some shell command is always extremely fragile.
Therefore, I am looking for an alternative way to solve this problem that does not rely on
shell-command or similar, but rather directly interrogates the ancestors of
(emacs-pid) (using the underlying OS's
getppid function somehow). This would entail traversing the sequence of
(emacs-pid)'s ancestors until finding either one whose associated command is
screen2 or one whose
pid is 1 (i.e. it's the root process).
1 Here and below, I use the expression
<EMACS_PID> as a placeholder for the integer
2 Admittedly, the problem of determining, in a robust way, that a particular PID corresponds to a GNU-screen process may already be pretty non-trivial.