iTerm2 icon indicating copy to clipboard operation
iTerm2 copied to clipboard

set $ITERM2_COPROCESS env var inside coprocesses

Open rolandwalker opened this issue 12 years ago • 4 comments

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.

rolandwalker avatar Jul 27 '13 23:07 rolandwalker

I noticed this old PR, squashed and rebased it.

rolandwalker avatar Jun 10 '14 19:06 rolandwalker

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.

gnachman avatar Jun 11 '14 16:06 gnachman

So the correct implementation would

  • memcpy global environ before forking
  • manually add a pointer to "ITERM2_COPROCESS_TTY=blah" to the copy
  • defend against the corner case where $ITERM2_COPROCESS_TTY was already set
  • execle with the copy

rolandwalker avatar Jun 11 '14 18:06 rolandwalker

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.).

gnachman avatar Jun 11 '14 21:06 gnachman