Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

interrupt

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?

like image 207
Aakash Avatar asked Jun 10 '10 11:06

Aakash


2 Answers

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.

like image 177
Luhar Avatar answered Sep 19 '22 18:09

Luhar


I assume that you are playing your java program with a Linux/Unix box. To run your application as a daemon, you can try

nohup java YourJavaClass &

To stop your application, you can either:

kill [psIdofYourApplication]

or

fg [your application job Id]
Ctrl-C

If you want to do some postprocessing after the application receiving 'kill/stop' signal. check out addShutdownHook(Thread hook)

Or sun.misc.SignalHandler

like image 42
Kent Avatar answered Sep 18 '22 18:09

Kent