How to find which Tmux session a process belongs to?

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.


Solution 1:

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

Solution 2:

This shell snippet works pretty well for me (you'll need the pstree utility as well):

for s in `tmux list-sessions -F '#{session_name}'` ; do
  echo -e "\ntmux session name: $s\n--------------------"
  for p in `tmux list-panes -s -F '#{pane_pid}' -t "$s"` ; do
    pstree -p -a -A $p
  done
done

For two tmux sessions with two vim's each, I get this output:

tmux session name: 0
--------------------
zsh,3444
  `-vim,3467 file_1
zsh,3474
  `-vim,3495 file_2

tmux session name: 1
--------------------
zsh,3526
  `-vim,3547 file_3
zsh,3554
  `-vim,3576 file_4

Solution 3:

Iterating using the response from Tor, a small bash snippet to get the session, window and pane where a particular PID is running:

export PID=1161102; for s in `tmux list-sessions -F '#{session_name}'` ; do
  for p in `tmux list-panes -s -F '#{pane_pid}' -t "$s"` ; do
    pstree -h -p -a -A $p | grep "[,]$PID" && tmux list-panes -s -t "$s" -f "#{==:#{pane_pid},$p}" -F '#{session_name}: #{window_index}.#{pane_index}'
  done
done

Example output:

  `-skydive,1161102 analyzer -c skydive.yml
SESSIONNAME: 2.3