Linux остановить процесс java

Linux остановить процесс java

How to kill a background Java process under the Linux system

First use the PS command to find the process ID of the Java process, then use the kill command to kill. The command is as follows:

Understand the essence of Java processes

The run of the Java program requires a runtime environment, namely: JVM, starting a Java process, starting a JVM. Therefore, the so-called stop Java process, essentially the JVM is closed.
So what is the case caused JVM to close?
JVM close:

Normally close: System.exit (0) or Ctrl + C or Kill (-15) SIGNTERM signal

Abnormal shutdown: runtimeException or OOM

Forced shutdown: Kill -9 Signterm signal or runtime.getRuntime (). Halt () or power down or system shutdown or system Crash

(1) Java system.exit () exits the program

Exit the program in Java, often use system.exit (1) or system.exit (0), where the value of Status is 0 represents normal exit, non-zero representative abnormality exits. Using this method can implement the exit function of the program in the graphical interface programming.

The exit (int) method terminates the currently running Java virtual machine, the parameter is interpreted as a status code. According to the convention, the state code of non-0 indicates an abnormality terminated. Moreover, this method will never return normally. This is the only situation that can exit the program does not perform Finally.

(2) Differences between Linux Kill -9 and Kill-15

Kill -9 PID is the operating system to force a process from the kernel level.

Kill -15 PID can understand that the operating system sends a notification to tell the application to actively shut down.

The effect of SIGNTERM (15) is normal exit process and can be blocked or callback before exiting. And it is Linux default program interrupt signal.

Kill -15 PID (default)
After executing the instruction, the operating system sends a SIGTERM signal to the corresponding program. When the program receives the signal, the following may occur:
The current program stops immediately;
The program releases the corresponding resources and then stops;
The program may continue to run.
Most programs will release their resources first, then stop. But there are programs that can continue to do other things after receiving the amount, and these things can be configured. If the program is waiting for IO, it may not be a response immediately. That is, 15) Sigterm may be blocked, ignored.

kill -9 pid
If 15) can SIGTERM not respond? That 9) Sigkill is the killing signal, and most of the ROOT will use this command directly, but do not recommend this.
Summary: Before using Kill -9, you should use Kill -15 to give the target process a chance to clean up. If not, some incomplete files or status may be left, which affects the restart of the service.

How should I stop Java processes correctly?

In general, stop a process only needs to kill the process.
However, in some cases you might need to perform some data saved or resource release before JVM shutdown, and you can’t directly force the Java process.

Читайте также:  Linux read only mode

1. For several cases of normal shutdown or abnormal shutdown, the JVM is closed, and the registered closed hook is called, based on this mechanism, we can put the sweeping work in closing the hook, and make our application security quit. Moreover, based on platform versatility, it is recommended to use system.exit (0) to exit JVM using System.exit (0).
2. For several cases for mandatory shutdown: The system is turned off, the operating system will notify the JVM process waiting to be closed, once waiting timeout, the system will force the JVM process; kill -9, runtime.halt (), power off, system CRASH The way the way will not discuss the JVM process directly, and the JVM does not have the opportunity to perform the sweeping work.

In summary:
1. Unless it is very sure that the Java process does not need to be performed before the Java process, it is strongly not recommended to use Kill -9 such simple violence to stop the Java process (except for the system shutdown, system Crash, power off, and runtime.halt () We can’t do it.).
2. No matter how, you should register to close the hook in the Java process, and do your best to do some good things before you get out of the Java process (actually, most of you need this).

Источник

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 .

Читайте также:  Astra linux обновление драйверов видеокарты

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 .

Источник

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(); >> > 

Источник

Читайте также:  Расположение ssh ключей linux

How to stop the execution of Java program from Command line?

My main field is .Net but recently I have got something to do with Java. I have to create a shell utility in Java that could run in background reading few database records after specified duration and do further processing. It’s a kind of scheduler. Now I have few concerns: How to make this work as a service. I want to execute it through a shell script and the utility should start running. Off course the control should get back to the calling script. Secondly, eventually i may want to stop this process from running. How to achieve this? I understand these are basic question but I really have no idea where to begin and what options are best for me. Any help / advise please?

5 Answers 5

I would go for the running the program using a scheduler or a service. However, if you wish to use a bat file and do this programmatically, I have outlined a possible approach below:

In your Java program, you can get the PID programmatically, and then write it to a file:

public static void writePID(String fileLocation) throws IOException < // Use the engine management bean in java to find out the pid // and to write to a file if (fileLocation.length() == 0) < fileLocation = DEFAULT_PID_FILE; >String pid = ManagementFactory.getRuntimeMXBean().getName(); if (pid.indexOf("@") != -1) < pid = pid.substring(0, pid.indexOf("@")); >BufferedWriter writer = new BufferedWriter(new FileWriter(fileLocation)); writer.write(pid); writer.newLine(); writer.flush(); writer.close(); > 

You can then write a stop .bat file that will kill the running program in windows. You could do something like:

setlocal IF EXIST app.pid FOR /F %%i in ('type app.pid') do TASKKILL /F /PID %%i IF EXIST app.pid DEL app.pid endlocal 

Of course, app.pid is the file written by the Java method above.

I am not sure how you would be able to write a script that launches a java program, and reverts control on termination. I would be interested to see if anybody has a solution for that.

Источник

Оцените статью
Adblock
detector