18 January 2008

Associating PIDs with Open Sockets on MacOS X

For years I've used netstat to determine which process is holding onto an open socket. That is, until MacOS X came along. I really like MacOS X but it drives me nuts at times when I find little differences like this that I've relied upon for so long. I know that this due to my lack of familiarity to the differences between Linux and BSD. Anyway, I recently stumbled upon an option while reading the man page for lsof that made me think it might substitute for this missing functionality:


-P This option inhibits the conversion of port numbers
to port names for network files. Inhibiting the
conversion may make lsof run a little faster. It is
also useful when host name lookup is not working
properly.


So I gave it a shot (wrapped for display):


$ lsof -P | grep 61616
java 7457 bsnyder 33u IPv6 0x39237f8 0t0
TCP *:61616 (LISTEN)
java 7457 bsnyder 43u IPv6 0x6278a24 0t0
TCP [::127.0.0.1]:55496->[::127.0.0.1]:61616 (ESTABLISHED)
java 7457 bsnyder 44u IPv6 0x642c8c4 0t0
TCP [::127.0.0.1]:61616->[::127.0.0.1]:55496 (ESTABLISHED)


Notice the PID in column two of the output above. This is can be incredibly useful especially when piped to other utilities (wrapped for display):


$ ps ax | grep `lsof -P | grep 61616 | awk {'print $2'} \
| uniq`
7457 p6 S+ 0:09.10
/System/Library/Frameworks/JavaVM.framework/Home/bin/java -Xmx512M
-Dorg.apache.activemq.UseDedicatedTaskRunner=true
-Dderby.system.home=/Users/bsnyder/apache-activemq-5.0.0.5


Voila! Now I can see what process is holding open port number 61616 (but I already knew that ;-) ).

Now, if I can just find a way to use the --forest option on the ps utility on MacOS X. Using ps -ef --forest on Linux is incredibly helpful yet unavailable on MacOS X. Anybody have any suggestions?

No comments:

Post a Comment