Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send Ctrl-C to process open by Java

Tags:

java

windows

Under Windows OS.

I start a sub-process via a Runtime.getRuntime().exec(); I want to send a "ctrl-c" to the process to stop it.

I did a small example, with Runtime.getRuntime().exec("ping google.com -n 100000"); The code can be found there : http://pastebin.com/f6315063f

So far, I tried to send the char '3' (ctrl-C character) via Process outputStream.

Here is a bit of code:

 cmd = re.exec("ping google.com -n 10000"); 
 out = new BufferedWriter (new OutputStreamWriter(cmd.getOutputStream()));
 input =  new BufferedReader (new  InputStreamReader(cmd.getInputStream()));


 char ctrlBreak = (char)3;
 //Different testing way to send the ctrlBreak;
 out.write(ctrlBreak);
 out.flush();
 out.write(ctrlBreak+"\n");
 out.flush();

I don't want to kill the process, I just want to send a Ctrl-C signal. How can I do that?

like image 406
Nettogrof Avatar asked Dec 02 '09 21:12

Nettogrof


People also ask

How do I use Ctrl C in Java?

The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System. exit) method is invoked, or. The virtual machine is terminated in response to a user interrupt, such as typing Ctrl + C , or a system-wide event, such as user logoff or system shutdown.

How do you execute a process in Java?

Process process = Runtime. getRuntime(). exec("processname"); Both of these will code snippets will spawn a new process, which usually executes asynchronously and can be interacted with through the resulting Process object.

How do you terminate a process in Java?

If you start the process from with in your Java application (ex. by calling Runtime. exec() or ProcessBuilder. start() ) then you have a valid Process reference to it, and you can invoke the destroy() method in Process class to kill that particular process.


1 Answers

I believe Ctrl-C is caught by the shell and translated into a signal (SIGINT) which is sent to the underlying process (in this case your spawned process).

So I think you'll need to get the process id and then send the appropriate signal to that process. This question appears to be very similar and points to various resources of use.

like image 121
Brian Agnew Avatar answered Sep 21 '22 08:09

Brian Agnew