Tmux – How to Find Which Tmux Session a Process Belongs To

processtmuxunix

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.

Best Answer

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/.*,//').

Related Question