Команда закрытия консоли java

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.

Читайте также:  Sorting list of strings python

Источник

System.exit() в Java – что это?

Java – язык программирования, имеющий множество приложений. При программировании для одного из этих приложений вы можете застрять на каком-то этапе этой программы. Что делать в этой ситуации? Есть ли способ выйти в этой самой точке? Если эти вопросы вас беспокоят, вы попали в нужное место.

Что вы можете сделать, это просто использовать метод System.exit(), который завершает текущую виртуальную машину Java, работающую в системе.

Как вы выходите из функции в Java?

Вы можете выйти из функции, используя метод java.lang.System.exit(). Этот метод завершает текущую запущенную виртуальную машину Java (JVM). Он принимает аргумент «код состояния», где ненулевой код состояния указывает на ненормальное завершение.

Если вы работаете с циклами Java или операторами switch, вы можете использовать операторы break, которые используются для прерывания / выхода только из цикла, а не всей программы.

Что такое метод System.exit()?

Метод System.exit() вызывает метод exit в классе Runtime. Это выходит из текущей программы, завершая виртуальную машину Java. Как определяет имя метода, метод exit() никогда ничего не возвращает.

Вызов System.exit (n) фактически эквивалентен вызову:

Функция System.exit имеет код состояния, который сообщает о завершении, например:

  • выход (0): указывает на успешное завершение.
  • выход (1) или выход (-1) или любое ненулевое значение – указывает на неудачное завершение.

Исключение: выдает исключение SecurityException.

Примеры

package Edureka; import java.io.*; import java.util.*; public class ExampleProgram< public static void main(String[] args) < int arr[] = ; for (int i = 0; i < arr.length; i++) < if (arr[i] >= 4) < System.out.println("Exit from the loop"); System.exit(0); // Terminates JVM >else System.out.println("arr["+i+"] = " + arr[i]); > System.out.println("End of the Program"); > >

Выход: arr [0] = 1 arr [1] = 2 arr [2] = 3 Выход из цикла

Объяснение: В приведенной выше программе выполнение останавливается или выходит из цикла, как только он сталкивается с методом System.exit(). Он даже не печатает второй оператор печати, который говорит «Конец программы». Он просто завершает программу сам.

package Edureka; import java.io.*; import java.util.*; public class ExampleProgram< public static void main(String[] args) < int a[]= ; for(int i=0;i > > >

Вывод: array [0] = 1 array [1] = 2 array [2] = 3 array [3] = 4 Выход из цикла

Объяснение: В приведенной выше программе она печатает элементы до тех пор, пока условие не станет истинным. Как только условие становится ложным, оно печатает оператор и программа завершается.

Источник

Читайте также:  Open php file with ajax

How to quit a java app from within the program

public static void exit(int status)

Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.

This method calls the exit method in class Runtime. This method never returns normally.

The call System.exit(n) is effectively equivalent to the call:

Runtime.getRuntime().exit(n)

The «0» lets whomever called your program know that everything went OK. If, however, you are quitting due to an error, you should System.exit(1); , or with another non-zero number corresponding to the specific error.

Also, as others have mentioned, clean up first! That involves closing files and other open resources.

As Chris states, System.exit(1) (or any other number) is if you want to indicate that it closed due to an error. System.exit(0) indicates that the program closed normally. You can also change 1 to any number you like, then when you are running your application from a script you can determine if there was an error.

System.exit(int i) is to be used, but I would include it inside a more generic shutdown() method, where you would include «cleanup» steps as well, closing socket connections, file descriptors, then exiting with System.exit(x) .

System.exit() is usually not the best way, but it depends on your application.

The usual way of ending an application is by exiting the main() method. This does not work when there are other non-deamon threads running, as is usual for applications with a graphical user interface (AWT, Swing etc.). For these applications, you either find a way to end the GUI event loop (don’t know if that is possible with the AWT or Swing), or invoke System.exit() .

Читайте также:  Java таблица с данными

Using dispose(); is a very effective way for closing your programs.

I found that using System.exit(x) resets the interactions pane and supposing you need some of the information there it all disappears.

I agree with Jon, have your application react to something and call System.exit().

  • you use the appropriate exit value. 0 is normal exit, anything else indicates there was an error
  • you close all input and output streams. Files, network connections, etc.
  • you log or print a reason for exiting especially if its because of an error

The answer is System.exit(), but not a good thing to do as this aborts the program. Any cleaning up, destroy that you intend to do will not happen.

There’s two simple answers to the question.

This is the «Professional way»:

//This just terminates the program. System.exit(0); 

This is a more clumsier way:

//This just terminates the program, just like System.exit(0). return; 

System.exit(0); return; is good too, the return prevents any ruther code from being run before the System can exit, otherwise you’d need a flag (.. i.e. if (!called_exit) < further code after exit statement >

Runtime.getCurrentRumtime().halt(0); 

From the Javadoc for halt : «This method should be used with extreme caution. Unlike the exit method, this method does not cause shutdown hooks to be started and does not run uninvoked finalizers if finalization-on-exit has been enabled. If the shutdown sequence has already been initiated then this method does not wait for any running shutdown hooks or finalizers to finish their work.» In short, you shouldn’t need to use halt , you should prefer exit .

System.exit() will do what you want. But in most situations, you probably want to exit a thread, and leave the main thread alive. By doing that, you can terminate a task, but also keep the ability to start another task without restarting the app.

System.exit(ABORT); Quit’s the process immediately.

Источник

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