Case in point is editing a configuration file in vim and inadvertently leaving it open. Then you go about your business, switch around in different Tmux sessions, eventually edit the same file from another session and vim will tell you a .swp file already exists.

Now, how do you find which Tmux session the other vim holding the file open is in? Findw seems to only search through active session windows.

link|improve this question
feedback

1 Answer

up vote 1 down vote accepted

lsof /path/to/.file.swp will show the process ID of the offending vim process. If you want to write a script, use pid=$(lsof -Fp "$swp_file"); pid=${pid#p} to get just the process ID.

Then ps 12345 where 12345 is the process ID will show some information about the process, in particular what tty it's running on (ps -o tty= -p $pid in a script). The tty uniquely identifies a tmux window (assuming the process is running inside tmux), but I don't know how to go from the tty name to the tmux session.

What would give you the tmux session is the value of the TMUX environment variable in the vim process. The session number is the last number, after the last comma.

Most unices have a way to find out the environment of a process, but the way differs between unix variants. On Linux, you can use </proc/$pid/environ grep -z '^TMUX=' to show the value of $TMUX in process $pid, so you can extract the session number as $(</proc/$pid/environ grep -z '^TMUX=' | sed 's/.*,//').

link|improve this answer
yes indeed, this basically works, at least for scenario when original vi process isn't sudoed. /proc/$pid/environ was new to me, good thinking on that. getting the session value as a number is good enough since the session id letters >9 simply increase alphabetically. – lkraav Nov 19 '10 at 22:01
when using sudo to launch the hypothetical vi process to find session by, it looks like it needs to have sudo -E for the TMUX variable to travel into it's environ. – lkraav Nov 19 '10 at 22:09
@lkraav: Best: use sudoedit instead of sudo vim. Also useful to know for other cases: either use sudo -E or put Defaults !env_reset in /etc/sudoers. In a pinch: find out the parent process of vim, which is likely to be a shell running in the same tmux window, and get its TMUX variable. – Gilles Nov 19 '10 at 22:26
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.