Friday, October 17, 2008

Find the UNIX Process ID given a port number

One of my colleagues had started the MWA server (telnet server) and it was running on port number 9198. However, when I queried the processes (ps -ef | grep mwa), I could not find the process which had kick started the MWA server.

This had me thinking and I resolved to find the process ID. However, the utility lsof was not installed on the OS (Sun Sparc Solaris 5.10) . When I probed further (googled! actually), I found a script on onlineappsdba, which I found helpful.

I had to modify that script suitably to exclude processes not owned by the current user. I also referred another blog, to complete my script.

______________________________________________________

#
# Make sure the logfile directory exists
#
if [ ! -d ${HOME}/bkp/log ]; then
mkdir -p ${HOME}/bkp/log
fi;

if [ $# -ne 1 ]; then
echo "To run the program, please provide the port number as the arguement"
printf "\n\t ${usage} \n\n"
exit 1;
fi

port_num="$1"


echo
printf "\n Finding the PID given the port number '${port_num}'.............. \n"
echo

for i in `ls -l /proc | grep ${cur_user} | awk '{print $9}'`
do
pfiles $i | grep AF_INET | grep ${port_num}
if [ $? -eq 0 ]
then
echo "Port ${port_num} owned by pid $i" >> ${LOG_DIR}/pid_from_port.txt
else
continue;
fi
done

clear
if [ -s ${LOG_DIR}/pid_from_port.txt ]; then
echo
cat ${LOG_DIR}/pid_from_port.txt
echo
else
echo
echo "Can not find the process that owns the port ${port_num}"
echo
fi


# Remove the temporary file.
rm -f ${LOG_DIR}/pid_from_port.txt
______________________________________________________

No comments: