For finding what uses a file, I'm an 'fuser' kid but lsof is fine too. Using posh right now, so had to make my own:<p><pre><code> function fuser($relativeFile){
$file = Resolve-Path $relativeFile
foreach ( $Process in (Get-Process)) {
foreach ( $Module in $Process.Modules) {
if ( $Module.FileName -like "$file*" ) {
$Process | select id, path
}
}
}
}
</code></pre>
In use:<p><pre><code> > fuser .\node_modules\
Id Path
-- ----
2660 C:\Program Files\nodejs\node.exe
</code></pre>
Since it's object pipelining, you can:<p><pre><code> > fuser .\node_modules\ | kill</code></pre>
<i>lsof -i -n -P</i> is a regular "reflex" command whenever I'm trying to figure out why a daemon I've just setup isn't responding to requests (immediately answers the questions: is it running? and, if yes, under what privs? and on what interface?).<p>That together with a dump of active iptables rules normally results in an immediate fix for 90% of "why can't I connect to X" problems :)
Although a bit rare in my usage, I have found basic use of lsof quite useful when needed. I haven't even tried many command line options. The options it provides really seem comprehensive. I have also found similar tools on Windows (like WhoLockMe or Process Explorer) quite useful.
s/Unix/Linux/<p>The following can be adapted to provide other information: whatever procfs provides. This is a rough equivalent of "pgrep -fl .|less". <i>Work-in-progress</i>. Don't know if Linux grep has "-a" option.<p><pre><code> #! /bin/sh
# Almquist clone, not Bash
case $# in
0)
exec grep -a . proc/[0-9]*/cmdline \
|exec tr '\000' '\040' \
|exec sed '
/grep -a .* proc/d;
#parent: '"$$"';
s/proc./ /;
s/\/cmdline:/ /;
' \
|exec less
;;
*)
exec grep -a . proc/[0-9]*/cmdline \
|exec tr '\000' '\040' \
|exec grep $@ \
|exec sed '
/grep '"$@"'/d;
s/proc./ /;
s/\/cmdline:/ /;
' \
|exec less
esac</code></pre>
lsof is my go-to command for "why won't this drive unmount?". That alone makes it incredibly useful.<p>Also, back in the bad old days, 'lsof | grep snd' helped track down what the hell was hogging my sound card (setting up proper mixing has made that a distant memory, though).