set $ITERM2_COPROCESS env var inside coprocesses
It might be nice for coprocesses to be able to detect that they are being run in that environment.
This patch sets an environment variable $ITERM2_COPROCESS.
The value might as well hold something useful: ttyname() from the originating interactive terminal.
I noticed this old PR, squashed and rebased it.
Sadly, it is not safe to call setenv() between fork and exec. Only the functions listed in the sigaction man page in the "NOTE" section may be called. In practice, this means using execle() instead of execl() when you want to set an environment variable.
The reason is that in a multithreaded program (which we are) another thread might have a mutex locked at the time of fork() (specifically, a mutex owned by libc). In the child process, that mutex will be locked forever since the child process only gets a single thread (the one where fork was called). The call to setenv() acquires a mutex, and will deadlock in this case.
So the correct implementation would
- memcpy global
environbefore forking - manually add a pointer to "ITERM2_COPROCESS_TTY=blah" to the copy
- defend against the corner case where
$ITERM2_COPROCESS_TTYwas already set execlewith the copy
I think that's right. Let's call it ITERM2_COPROCESS so we can add more info to it if desired later on (like profile name, etc.).