0

I have a shell script running through a process runtime on Java. This Shell Script only stops when you hit CTRL+C Right now I catch the InputStream from the script in a JTextArea. but I can't send CTRL+C.

When you run CTRL+C on a Shell Konsole the script stops and sends back information. and this information is the one that I Can't Catch.

So How can I Send CTRL+C Through Process runtime? How can I catch the Inputstream from CTRL+C?

File dirw = new File("/home/mydir/sh/");
Runtime runtime = Runtime.getRuntime();
Process process = null;
process = runtime.exec("./start_test.sh", null, dirw);

OutputStream outp = new OutputStream(process.getOutputStream());
InputStreamReader isr = new InputStreamReader(process.getInputStream());
BufferedReader br = new BufferedReader(isr);
String line = null;

int cont = 1;
while ((line = br.readLine()) != null) {
        jtextarea.append("LineOK " + line + "\n");
         if( cont == 10) {
             outp.write(3);    //sending Ctrl+C
             outp.flush();
             cont =0;
         }
         cont ++;
}
Mwiza
  • 7,780
  • 3
  • 46
  • 42
Mau86
  • 1
  • 1
  • 2

1 Answers1

2

CTRL+C is a command sent from user to shell. When shell receives it, it sends SIGINT to the foreground process.

To do this in Java use Process.sendSignal(pid, Process.SIGNAL_QUIT) - this only works on Android.

Update: the above command is wrong as it's only available on Android.

The correct way is to send kill -2 pid. Beware: this is UNIX-only solution. Another problem is getting the pid (process id). It turns out there is no OS-agnostic solution to it: How to get PID of process I've just started within java program?

The solution is to resort to OS-dependent hacks as mentioned in the link (getting pid from Process via reflection).

Mwiza
  • 7,780
  • 3
  • 46
  • 42
Peter Knego
  • 79,991
  • 11
  • 123
  • 154
  • I'm working with Serial Port and Process does not have the method sendSignal – Mau86 May 02 '11 at 17:57
  • I try to do it as you suggested but it didn't work. I found the Process Id. but when i want to kill it (typing Kill -SIGINT PID) nothing happend on the konsole frame, i'm still receiving information as if I were still running the program but on the Process table (KsysGuard) it did kill it. I also try differente Signals but i got the same results. As I told you before on Konsole when you hit Ctrl+c the program stops running and sends back information. – Mau86 May 03 '11 at 15:44