I have a process that listens on a TCP port (?0003). From time to time it crashes - badly. It stops working, but continues hogging the port for some time, so I can't even restart it. I'm looking to automate this.

What I do right now is:

netstat -ntlp |grep -P "\*\:\d0003"

To see what the PID is and then:

kill -9 <pid>

Does anyone have a script (or EXE for that matter) that would link the two steps together, ie. parse the PID from the first command and pass it to the second?

migrated from stackoverflow.com Mar 15 '10 at 1:09

This question came from our site for professional and enthusiast programmers.


You also can do by that way :

kill -9 $( lsof -i:?0003 -t )
  • Very elegant! I often use things like lsof -ni:80,443 - but wasn`t aware of the switch -t thanks! – ThorstenS Mar 15 '10 at 6:33
  • Indeed. the ? wildcard doesn't work on my version of lsof, but multiple -i options work. Changing the accepted answer to this one. – EMP Mar 15 '10 at 22:26
kill $(netstat -ntpl 2>/dev/null | egrep "^tcp  .*:[0-9]0003"|awk '{print $7}'|cut -d / -f 1 )

You may do kill -9 instead of you think the -9 is required. I redirect the netstat stderr because it omits a message when run as non-root which is unimportant for this purpose. I include tcp in the regex to filter out tcp6.

  • Awesome, that's exactly what I need - thanks! – EMP Mar 15 '10 at 0:25
  • 2
    Using back-apostrophes is deprecated, because this leads to quoting-related problems and mistakes. Switch to $() and turn using it into a habit. – przemoc Mar 15 '10 at 0:30

there you go, one line for you

netstat -ntlp | awk '$4~/:*0003$/{gsub(/\/.*/,"",$NF);cmd="kill -9 "$NF;system(cmd)}'
  • +1 Works very nicely, thank you. I'm accepting Peter Lyons' answer, just because it's one line and can be pasted into the command-line more easily. :) – EMP Mar 15 '10 at 0:26
  • Alright then, another +1 here on Server Fault. – EMP Mar 15 '10 at 22:23

I take it that the python command is just the first term in the full command, right? If you have the name of the script being run you can look at something like pgrep -f

If you are sure of uniqueness, you can also use the related pkill -f


What about killall <command> are there more than one of these processes?

If that don't work try:

PID=`netstat -ntlp |grep -P "\*\:\d0003"`; kill -9 $PID

That should do the trick.

  • No, there's just one, and I can't go by the process name, because it's typically just "python" or "java". – EMP Mar 15 '10 at 0:05

Maybe the fuser command with the -k and -n options may help. Say "man fuser" for more info.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.