0

I use Amazon EC2 instances to perform some complex computation by using the AWS Java SDK, these computations might take so long sometimes. Hence, I need to kill the process running on the EC2 instance remotely from my Java code so that I can reuse the same instance for another task without needing to stop and start the instance.

The problem with stop and start, is that Amazon treat partial hours as complete hours, so my aim is to make my code more cost effective.

I use SSH to connect with my EC2 instances and that is how I pass commands to be executed there. I doubt that if I disconnect the SSH connection and connect to it again, it would kill whatever process was running there.

In short, what I need is away of doing Ctrl+C but from within my Java code (without user intervention). Is that possible?

EDIT: To clarify, the computation is executed by a separate tool installed on the Linux EC2 instance. So I just pass the command to start this tool, then the command line waits until its finished and shows the results. On manual usage scenario, I can click Ctrl+C on linux command line and will get control of the command line back. But in my case, I want to do similar thing from java code if possible.

Sami
  • 7,797
  • 18
  • 45
  • 69
  • This is a possible duplicate and will probably solve your issue: http://stackoverflow.com/questions/6356340/killing-a-process-using-java – gimg1 Oct 11 '13 at 10:42

2 Answers2

0

Use the SIGAR library to scan the process list on a machine and kill your process.

Use getProcList() to get all process IDs, getProcArgs() to get the full command line of each process, and kill() to kill the relevant process or processes.

So if a task is running and you want to kill it, SSH again into the machine and run your SIGAR based process killer.

Barak
  • 3,066
  • 2
  • 20
  • 33
0

One dirty/functional way would be to kill your process via SSH using the java Runtime to execute it.

Something like

Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec("ssh user@host command");

So in your case, if you know the program's PID (1234 for example):

Process p = runtime.exec("ssh user@host kill 1234");

Or if you know the program's name:

Process p = runtime.exec("ssh user@host pkill my_program_name_x64");

Note that you usually have to give absolute paths to the executables invoked via runtime.

So you'll have to replace ssh by something like /bin/ssh or /usr/bin/ssh as well as for kill and pkill or killall.

Thibault D.
  • 10,041
  • 3
  • 25
  • 56