- Linux Script to Kill Java Process
- Run and kill java program in background in Linux
- Kill a java process (in linux) by process name instead of PID
- How to quickly kill java processes in bash?
- Stop Java from killing Bash script that started it
- Kill a Specific set of process from shell script
- How to stop java process gracefully?
- 7 Answers 7
- Kill only one Java process
- 8 Answers 8
Linux Script to Kill Java Process
EDIT: To kill a particular java process running your specific jar use this regex based pkill command:
pkill -f 'java.*lnwskInterface'
Run and kill java program in background in Linux
javaProgram &
pid=$!
echo $pid >/var/run/javaProgram.pid
kill $(cat /var/run/javaProgram.pid)
Kill a java process (in linux) by process name instead of PID
Here is the command to kill the Java process by is Process Name instead of its ProcessID.
kill -9 `jps | grep "DataNode" | cut -d " " -f 1`
Let me explain more, about the benefit of this command. Lets say you are working with Hadoop cluster. Its often required that you check java daemons running with jps command. Lets say when you give this command on worker nodes, you see following output.
1915 NodeManager
18119 DataNode
17680 Jps
Usually, if we want to kill DataNode process, we would use following command
But, it is little bit difficult to type the PID , to use kill command. By using the command, given in this answer, it is easy to write the name of the process. We can also prepare shell scripts to kill commonly used deamons in hadoop cluster,
or we can prepare one shell script and can use parameter as process name.
How to quickly kill java processes in bash?
You can save the PIDs when you start the processes so you can use them later:
nohup ./start-gossip &
START_GOSSIP_PID=$!
nohup ./start &
START_PID=$!
nohup ./start-admin &
START_ADMIN_PID=$!
.
kill -9 $START_GOSSIP_PID
kill -9 $START_PID
kill -9 $START_ADMIN_PID
This has the advantage (over pkill ) of not killing off any other processes that coincidentally have similar names. If you don’t want to perform the kill operation from the script itself, but just want to have the PIDs handy, write them to a file (from the script):
echo $START_GOSSIP_PID > /some/path/start_gossip.pid
Or even just do this when you launch the process, rather than saving the PID to a variable:
nohup ./start-gossip &
echo $! > /some/path/start_gossip.pid
Stop Java from killing Bash script that started it
Well, after a lot of searching and some prompting from the comments, I found that the issue lied with how the program was initially being started.
As mentioned in the update, the first run is always started by an ssh connection. I knew there was a slight problem with this ssh connection, as it seemed to hold onto the connection no matter what I did. It turns out that this was causing the problem that resulted in the Bash instance and the Java instance remaining attached.
The solution for this problem was found here: jsch ChannelExec run a .sh script with nohup «lose» some commands
After managing to get the initial setup to start with nohup properly, the issue has gone away.
Kill a Specific set of process from shell script
Not sure if this works but I think this is what it would look like based on Stephen P’s comment. This assumes the java program only spawns chrome processes as children and no other processes.
#!/bin/bash
$openjava=""
while true
do
java -jar uploadv2.jar &
$openjava="$openjava $!" # List of all java programs running
# The $! gets the most recently spawned process id
for process in $openjava
do
childProc="$childProc `pgrep -P $process`" #get chrome processes spawned by java
done
for tab in childProc
do
kill $tab #kill the child processes (chrome tabs)
done
done
How to stop java process gracefully?
How do I stop a Java process gracefully in Linux and Windows? When does Runtime.getRuntime().addShutdownHook get called, and when does it not? What about finalizers, do they help here? Can I send some sort of signal to a Java process from a shell? I am looking for preferably portable solutions.
I assume they mean they want to be given the chance to clean up an resources, release, locks, and flush any persistent data to disk before the program is killed.
7 Answers 7
Shutdown hooks execute in all cases where the VM is not forcibly killed. So, if you were to issue a «standard» kill ( SIGTERM from a kill command) then they will execute. Similarly, they will execute after calling System.exit(int) .
However a hard kill ( kill -9 or kill -SIGKILL ) then they won’t execute. Similarly (and obviously) they won’t execute if you pull the power from the computer, drop it into a vat of boiling lava, or beat the CPU into pieces with a sledgehammer. You probably already knew that, though.
Finalizers really should run as well, but it’s best not to rely on that for shutdown cleanup, but rather rely on your shutdown hooks to stop things cleanly. And, as always, be careful with deadlocks (I’ve seen far too many shutdown hooks hang the entire process)!
Unfortunately, this doesn’t seem to work on Windows 7 (64bit). I’ve tried using taskill, without the force flag, and encounter the following error: «ERROR: The process with PID 14324 could not be terminated. Reason: This process can only be terminated forcefully (with /F option).» Supplying the force option, «/f», obviously will close the process instantly.
Ok, after all the possibilities I have chosen to work with «Java Monitoring and Management»
Overview is here
That allows you to control one application from another one in relatively easy way. You can call the controlling application from a script to stop controlled application gracefully before killing it.
Here is the simplified code:
Controlled application:
run it with the folowing VM parameters:
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
//ThreadMonitorMBean.java public interface ThreadMonitorMBean < String getName(); void start(); void stop(); boolean isRunning(); >// ThreadMonitor.java public class ThreadMonitor implements ThreadMonitorMBean < private Thread m_thrd = null; public ThreadMonitor(Thread thrd) < m_thrd = thrd; >@Override public String getName() < return "JMX Controlled App"; >@Override public void start() < // TODO: start application here System.out.println("remote start called"); >@Override public void stop() < // TODO: stop application here System.out.println("remote stop called"); m_thrd.interrupt(); >public boolean isRunning() < return Thread.currentThread().isAlive(); >public static void main(String[] args) < try < System.out.println("JMX started"); ThreadMonitorMBean monitor = new ThreadMonitor(Thread.currentThread()); MBeanServer server = ManagementFactory.getPlatformMBeanServer(); ObjectName name = new ObjectName("com.example:type=ThreadMonitor"); server.registerMBean(monitor, name); while(!Thread.interrupted()) < // loop until interrupted System.out.println("."); try < Thread.sleep(1000); >catch(InterruptedException ex) < Thread.currentThread().interrupt(); >> > catch(Exception e) < e.printStackTrace(); >finally < // TODO: some final clean up could be here also System.out.println("JMX stopped"); >> >
Controlling application:
run it with the stop or start as the command line argument
public class ThreadMonitorConsole < public static void main(String[] args) < try < // connecting to JMX System.out.println("Connect to JMX service."); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi"); JMXConnector jmxc = JMXConnectorFactory.connect(url, null); MBeanServerConnection mbsc = jmxc.getMBeanServerConnection(); // Construct proxy for the the MBean object ObjectName mbeanName = new ObjectName("com.example:type=ThreadMonitor"); ThreadMonitorMBean mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, ThreadMonitorMBean.class, true); System.out.println("Connected to: "+mbeanProxy.getName()+", the app is "+(mbeanProxy.isRunning() ? "" : "not ")+"running"); // parse command line arguments if(args[0].equalsIgnoreCase("start")) < System.out.println("Invoke \"start\" method"); mbeanProxy.start(); >else if(args[0].equalsIgnoreCase("stop")) < System.out.println("Invoke \"stop\" method"); mbeanProxy.stop(); >// clean up and exit jmxc.close(); System.out.println("Done."); > catch(Exception e) < // TODO Auto-generated catch block e.printStackTrace(); >> >
Kill only one Java process
I usually run few Java applications, one for server running locally and other for some IDE like NetBeans. And from time to time, after lots of redeployments, my server get stuck on OutOfMemoryException so I need to kill Java process in order to reboot. So I do pkill -9 java but this also kills my running IDE which I don’t want to. So how do I kill only application linked to running server and not the other ones?I assume that they all are running under same process but there has to be some way how to distuingish them.
look at your process table (via top or ps ) and choose the right one and kill it by PID (kill -9 PID_number).
8 Answers 8
For killing a process that is associated with multiple processes, you need to kill that by using process id associated with that process.
To get the process id of that java process run
output of this command will give the list of java processes running on your system. Note down Process ID (PID) of that process whom you want to kill and run
If you want to kill ALL java processes by one command ps ax | grep java | grep -v ‘grep’ | cut -d ‘?’ -f1 | xargs kill -9
Instead of using ps and grep , you can use ps ‘s -C flag to select all commands listed with the name ‘java’. You may also want to use ps ‘s -f flag to print the full command name of each listed process. That way, you can see what each java process is actually doing. Here is the command in full: ps -fC java .
You could also use pgrep to list all java processes. pgrep -a java will return the PID and full command line of each java process.
Once you have the PID of the command you wish to kill, use kill with the -9 (SIGKILL) flag and the PID of the java process you wish to kill. Java doesn’t always stop when it receives a ‘SIGTERM’ signal (processes are allowed to handle ‘SIGTERM’), so sending it the ‘SIGKILL’ signal, which makes init kill the program without warning it first, is often necessary.
For example, if ps -fC java returns
UID PID PPID C STIME TTY TIME CMD jeff 9014 8890 0 08:51 pts/0 00:00:00 java IDE jeff 11775 8890 6 08:59 pts/0 00:00:00 java TestProgram
9014 java IDE 11775 java TestProgram
and you wish to kill java TestProgram , you should run kill -9 11775 .