How to find Tomcat's PID and kill it in python?
- by 4herpsand7derpsago
Normally, one shuts down Apache Tomcat by running its shutdown.sh script (or batch file). In some cases, such as when Tomcat's web container is hosting a web app that does some crazy things with multi-threading, running shutdown.sh gracefully shuts down some parts of Tomcat (as I can see more available memory returning to the system), but the Tomcat process keeps running.
I'm trying to write a simple Python script that:
Calls shutdown.sh
Runs ps -aef | grep tomcat to find any process with Tomcat referenced
If applicable, kills the process with kill -9 <PID>
Here's what I've got so far (as a prototype - I'm brand new to Python BTW):
#!/usr/bin/python
# Imports
import sys
import subprocess
# Load from imported module.
if __init__ == "__main__":
main()
# Main entry point.
def main():
# Shutdown Tomcat
shutdownCmd = "sh ${TOMCAT_HOME}/bin/shutdown.sh"
subprocess.call([shutdownCmd], shell=true)
# Check for PID
grepCmd = "ps -aef | grep tomcat"
grepResults = subprocess.call([grepCmd], shell=true)
if(grepResult.length > 1):
# Get PID and kill it.
pid = ???
killPidCmd = "kill -9 $pid"
subprocess.call([killPidCmd], shell=true)
# Exit.
sys.exit()
I'm struggling with the middle part - with obtaining the grep results, checking to see if their size is greater than 1 (since grep always returns a reference to itself, at least 1 result will always be returned, methinks), and then parsing that returned PID and passing it into the killPidCmd. Thanks in advance!