Process.destroy() is ignored

Hi all,
I have a problem using the method destroy() from class Process.
I created a simple thread as a class which implements interface Runnable. In method run() I start an external command using ProcessBuilder.start(). The command which is started writes output to stdout in an endless loop. I consume this output using class Scanner which iterates line-by-line through the stream displaying it by System.out.println().
If I try to stop the process with method destroy() nothing really happens. I checked Process.exitValue() which throws an IllegalThreadStateException saying that the process has not exited.
I searched the internet and found something about this problem: A process could only be destroyed if it does not write to stdout anymore. Is that true, because my process acts like an endless loop writing to stdout...
Thanks in advance
public class Starter implements Runnable {
    private volatile Thread thisThread;
    private ProcessBuilder processBuilder;
    private Process process;
    private Scanner scanner;
    public void start() {
        thisThread = new Thread(this);
        thisThread.start();
    public void stop() {
        thisThread.interrupt();
        process.destroy();
        System.out.println("EXIT: " + process.exitValue());
    public void run() {
        try {
            processBuilder = new ProcessBuilder("myCommand");
            processBuilder.redirectErrorStream(true);
            process = processBuilder.start();
            scanner = new Scanner(process.getInputStream());
            while (scanner.hasNextLine()) {
                String input = scanner.nextLine();
                System.out.println("Line: " + input);
            scanner.close();
        } catch (IOException e) {
            e.printStackTrace();
}

Thanks for the reply. I made the following changes:
    public void stop() {
        process.destroy();
        try {
            Thread.sleep(2000); // needed, otherwise the exception mentioned before is thrown
        } catch (InterruptedException e) {
            e.printStackTrace();
        thisThread.interrupt();
        System.out.println("EXIT: " + process.exitValue());
    }This code throws no exception anymore. I get a value from exitValue(). But my process is still running: I tried this without using method thisThread.interrupt(). The scanner should actually stop, because there is no further input to process.
Also a ps (I'm working on Linux) still shows my process.

Similar Messages

  • Process.destroy() doesn't work?

    Hey,
    I'm running Java 1.4 on Win 2k, and when I call process.destroy(), the process isn't killed. Here is my code:
    class MyRunner{
    public static void main (String [] args){
        Runtime rt = Runtime.getRuntime();
        Process pr = null;
        try{
          pr = rt.exec("cmd /c start cscript.exe "C:\\Test.vbs\"");
          System.out.println("Got started");
          Thread.sleep(20000);
        catch(Exception e){
        finally{
          System.out.println("I'm about to kill it");
          pr.destroy();
          System.out.println("Killed it.");
    }In the console, the output is:
    Got started.
    And then it waits 10 seconds before printing:
    I'm about to kill it
    Killed it.
    But the process isn't killed. Why?
    Thanks for any help

    The cmd process is killed (it was already finished most likely). The cscript.exe process cmd started is probably still running.
    See [http://www.computerhope.com/cmd.htm|http://www.computerhope.com/cmd.htm].
    Note that is not really related to Java.

  • Process.destroy does�nt work

    Hello!
    I have created a process the following way:
    Process process = Runtime.getRuntime().exec(cmd);
    It is intended to run as a background task while i�m doing other stuff. When the other things are taken care of I want to stop/kill the process and use the following line:
    process.destroy();
    Nothing happens, the process is still alive, how can I kill it?

    Are you trying to execute a batch file or a shell script? I'm having the same problem with batch/script processes.
    vhince
    Hello!
    I have created a process the following way:
    Process process = Runtime.getRuntime().exec(cmd);
    It is intended to run as a background task while i�m
    doing other stuff. When the other things are taken
    care of I want to stop/kill the process and use the
    following line:
    process.destroy();
    Nothing happens, the process is still alive, how can
    I kill it?

  • External process destroy on Windows XP

    Hello friends.
    I have a small program that launches external process (another java program), reads and processes process output until the process is destroyed (terminates). The program works fine on Windows 2000 - when external java program launched as separate Process terminates, an inputStream.readLine() call throws exception, and my program can continue. However on XP when external process terminates, it is not unloaded from memory, and inputStream.readLine() blocks forever...
    I run under lates JVM 1.4... Any ideas why? Has anyone encountered this problem before?
    try {                          
       Process p=Runtime.getRuntime().exec("java SomeProgram");
       in=new BufferedReader(new InputStreamReader(p.getInputStream()));
       while ((s=in.readLine())!=null) { // blocks on XP, works on Win2000
          // Process input
    } catch(IOException ioe) {
    } catch (Exception e) {
    }Any help appreciated.

    I have a similar problem with a small Java program running on Linux, so it may not be OS specific. The code is similar to yours, except that the file being read is produced by a third party. The third party claims to produce a new file every 5 minutes, and it takes about 30 seconds for them to produce the file.
    The program is supposed to run indefinitely -- it reads the file, then sleeps for 5 minutes, then reads the file again.
    Every so often, (like once every 24-36 hours), the program hangs indefinitely at the readLine() call.
    What's driving me crazy is that I've used the exact same idiom in numerous other circumstances and I've never encountered this problem.
    At first I thought that perhaps the file was being changed while my program was reading it. But under those circumstances I would have thought I'd get some kind of IOException, and I don't.
    I'm going to explore using the ready() method of BufferedReader... but I'm not sure if that will solve the problem.
    I'd also be very greatful for any input on this matter!
    - Dean

  • Exiting a Runtime Process without calling destroy()

    I have a child process that I have started with Runtime.getRuntime.exec(). Is there any way to stop this process without allowing the child process to run to completion or calling Process.destroy()?

    I have a child process that I have started with
    Runtime.getRuntime.exec(). Is there any way to stop
    this process without allowing the child process to
    run to completion or calling Process.destroy()?Not portably.
    If on Unix/Linux, you can exec some script code to run "ps" to find your process (perhaps by examining the command line) and send it a SIGTERM via "kill".

  • Is it possible to destroy process tree in Java?

    I am creating a process using Runtime.exec(). Newly created process spawns another process and that may spawn other processes. I want to kill all these child processes when my application exits.
    Process.destroy() only kills the immediate child.
    Is it possible in Java to kill process tree? or is there any other way of achieving it?
    Thanks
    Sudhan.

    Depending on your operating system, create a shell script file that will call the other processes. Create another shell script file that will kill the processes created. Use Runtime.exec() to call each shell script. Not exactly 100% portable, but you are using Runtime.exec() anyway.
    - Saish
    "My karma ran over your dogma." - Anon

  • Getting output of a process before destroying it . . . . .

    Currently I'm working on some code that runs a number of processes and if they run past a certian time constraint I use p.destroy() to kill them. However, I want whatever output they've produced thus far before I kill them. Trying to use p.getOutputStream causes my code to try an wait for all of the output to finish.
    here's a snipped of the code I'm using to time and kill the processes(the class extends TimerTask so it's invoked after a set period of time, where it kills the process I give it);
    public void run()
        isTimedOut = true;
        System.out.println( testName + ": TIMED OUT!!" );
        //    writeOutput(caseID);
        System.out.println("done writing output to log");
        p.destroy();
        System.out.println("process destroyed");
        timer.cancel();
    public void writeOutput( int caseID )
        try
            PrintStream scriptOut = new PrintStream(new BufferedOutputStream( new FileOutputStream(logdir + caseID + '-' + curStepType + '-' + System.currentTimeMillis())));
            //Writing the scripts output and stderr to the proper logfile
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            String s;
            //System.out.println( "ID: " + testName );
            while( (s=in.readLine())!= null )
                scriptOut.println( "ERROR: " + s);
                //System.out.println( "Script output: " + s );
            BufferedReader in1 = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String s2;
            //System.out.println( "ID: " + testName );
            while( (s2=in1.readLine())!= null )
                scriptOut.println( "OUTPUT: " + s2);
                //System.out.println( "Script output: " + s );
            scriptOut.close();
          }catch( Exception e )
            { e.printStackTrace(); }

    little help?

  • How to list all OS processes from a java program

    I want to list/kill all OS processes from a java program, or a part from all processes according to a filter on a name of process.
    a similar functionality is ps in Unix or taskkill in Windows XP.
    Thanks!

    Hi,
    I was looking for such lib, but finally I decided to accomplish the job with my fingers end ;-). It maigh be helful for u guys:
    // is written for x based OSs
    private static void killProcess(Process process) {
    if (process == null)
    return;
    process.destroy();
    private static void closeProcessStreams(Process process) {
    try {
    process.getErrorStream().close();
    } catch (IOException eyeOhEx) {
    private static void listPHPs() {
    Process proc = null;
    Runtime rt = Runtime.getRuntime();
    int exitVal = 0;
    try {     
    proc = rt.exec(" ps -C php"); // here use ur filter. issue "man ps" in linux for more info
    catch (Exception ex) {
    System.out.println(ex.getMessage());
    killProcess(proc);
    return;
    try {
    // process the return list of ur command
    InputStream stdReturnStr = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(stdReturnStr);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    String returnMsg = "";
    boolean firstLine = true;
    int[] allPIDs = new int[100]; // finally we have an array of PIDs
    int PIDCount = 0;
    while ( (line = br.readLine()) != null) {
    if (!firstLine){ // the first line is title, ignore it
    returnMsg += line + "\n";
    String PID = line.trim().split(" ")[0];
    System.out.println(PID);
    try{
    allPIDs[PIDCount] = Integer.parseInt(PID);
    PIDCount++;
    }catch(Exception ex){           
    else
    firstLine = false;
    System.out.println(returnMsg);
    catch (Exception t) {
    System.out.println(t.getMessage());
    killProcess(proc);
    return;
    try {
    exitVal = proc.waitFor();
    catch (Exception t) {
    System.out.println(t.getMessage());
    killProcess(proc);
    return;
    closeProcessStreams(proc);
    Thats it!

  • BI Content 7.57 SP4 Activating Process Chain

    Hi,
    I am trying to activate a process chain from BI content . My source system is ERP 6.0. While collecting objects for activating this Process Chain BW gives an errors. It says some of DTP and Transformations are missing. I have put two of the errors are at below.
    When i search these missing objects on the BI content these objects are not exist. Also on the BW system they are not exist. I could not find any solution for this problem.
    Can you please show me a way for solving this. I am stuck on this.
    I am trying to activate following Process Chain.
    Technical Name: 0HCM_FULL_P0EMPLOYEE
    Name : Load Data for InfoObject 0EMPLOYEE
    Error 1:
    Shadow object DTP_DYF4USYQ4EYMWILRMUGLXW2KG cannot be expanded; chain is inconsistent
    Message No. RSPC142
    Diagnosis
    You want to determine the objects that are source system-dependent for shadow object DTP_DYF4USYQ4EYMWILRMUGLXW2KG so that they can be inserted in the modified version of the process chain or of a referencing process. This was not possible.
    Error 2:
    Object DTP_ETKRN0DQM7QVOBZSVBC9J61HB (Data Transfer Process,DTPA) could not be collected for object 0HCM_FULL_P0EMPLOYEE (Process Chain,RSPC)
    Message No. RSO296
    Diagnosis
    You have collected objects in the BW Metadata Repository. Associated objects for the object 0HCM_FULL_P0EMPLOYEE of type Process Chain,RSPC have also been collected. Object DTP_ETKRN0DQM7QVOBZSVBC9J61HB of type Data Transfer Process,DTPA was among these objects. This object
    DTP_ETKRN0DQM7QVOBZSVBC9J61HB of type Data Transfer Process,DTPA, is not, however, available in the Metadata Repository.
    System Response
    Object DTP_ETKRN0DQM7QVOBZSVBC9J61HB of type Data Transfer Process,DTPA is ignored in further collections. The links for object 0HCM_FULL_P0EMPLOYEE of type Process Chain,RSPC are incomplete. This may result in not being able to activate this object.

    Hello experts
    I am not able to find support package name.
    When i click on package level button from SAPM tcode
    BI_CONT     703     0000     -     Business Intelligence Content.
    Is my BI_CONT add-on installed successfully?
    And also i am not able to see BI_CONT in imported packages list.

  • How to get process ID

    Hi,
    I am trying to run a process using runtime.exec() method. I want to know the process id of that process.
    Is there any way to get the process id? Please help me on this.
    Thank you.

    Renuka_Patil wrote:
    I am trying to run the cruisecontrol.bat file which is continuously building the files. now to stop building operation user ll have to close the command prompt (he can do it by pressing ctrl+c). but i want to close the command prompt on the click of button which is present on UI. So i want a process id to close the command prompt.
    Process.destroy() destroys the process
    Is there any other way of closing the command prompt? Please suggest.Is it at some point going to occur to you that since now at least three different people have suggested that you are doing a Bad Thing ™ , that you are in fact doing a Bad Thing ™ ?

  • How to stop a process that i have started in my prog to stop

    public class stopproc {
         public static void main(String args[]){
    Runtime rt = Runtime.getRuntime();
    try{
    Process process = rt.exec("start notepad");
    //Thread.sleep(1000);
    //process.destroy();
    }catch(Exception ex){}
    The above is the code where i am starting a notepad and want to destroy it..but it is not working..can u tell me why

    //process.destroy();
    That won't do anything because it is a comment, not a line of code.

  • Best way to close a Runtime.exec() process and how to handle closing it?

    I have multiple Runtime.exec() Processes running and am wondering what the best way it is to close them and take care of closing the resources. I see that Process.destroy() seems to be the way to terminate the Process - is finalize() the best way to close anything in that Process?
    Thanks

    I was involved with your other thread, so I think I know what you are trying to do.
    All Dr's answers are correct.
    Now you have a program A written by you that does Runtime.exec() of multiple instances
    of another program B written by you. You want A to somehow tell B to exit.
    You must use some kind of Inter Process Communication. If this is the only interraction
    between the two programs I can suggest two options. If you anticipate more
    interraction, you may want to look at other means (RMI, for instance, which was proposed
    by EJP in the other thread for starting B, is also useful in exchanging info).
    Solution 1:
    Start a thread in B and read stdin. A will write to stdin a command, such as QUIT.
    When B reads it, it does System.exit().
    Solution 2:
    Start a SocketServer in B that accepts connections on a separate thread.
    When A wants B to exit, it connects to it and writes a command such as QUIT.
    When B reads it, it does System.exit().
    You may note that QUIT is not the only command you can send from A to B, in case you will need more.
    Edited by: baftos on Nov 5, 2007 2:15 PM

  • Purchase requisition - no GR processing time

    Hi,
    when you create a purchase requisition in transaction ME21n the goods receiving processing time is considered (from the material master MM02).
    In some cases (e.g. Third-Party) we want that this GR processing time is ignored.
    Is there a possibility in the standard to set up this functionality?
    Or must we implement coding in an userexit or BAdi?
    Thanks for your help.

    SB,
    Purchase requisitions are not normally created in ME21.  For manual creation, you would normally use ME51, or ME51N for the Enjoy version.
    As far as I know, goods receipt processing time is specific to the Material/plant.  It is irrelevant to the source of the supply proposals.
    Keep in mind that purchase requisitions are often created by MRP. Your ME51 mod will most probably have no effect on these PRs.   During MRP, at the time when the PR is being created, the completion date has already been determined, but the source has not yet been determined.  In addition, not all purchase reqs are sourced.  Your programmers will have an interesting task ahead of them if you want to make MRP, during PR creation, to consider GRPT on selected PRs, based on source of the PR.  Good luck!
    Normally, if you wish to have sourced PRs act differently, depending on the source, you enter planned delivery time in the Purchase Info Record, and then configure your PRs to use Purchase Info record data rather than Material Master data.  This will not alter the finish date as GRPT will, but in some cases it gives you enough functionality to meet your business requirements.
    Rgds,
    DB49

  • SIGQUIT ignored / no thread dump in 1.5/5.0 ?

    Trying out 1.5 on a dual-xeon, Linux 2.4.27 machine. - 'java -version' returns:
    java version "1.5.0"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0-b64)
    Java HotSpot(TM) Client VM (build 1.5.0-b64, mixed mode, sharing)
    Java process seems to ignore 'kill -SIGQUIT' -- nothing to stderr/stdout, nothing to working directory. A thread dump would be really handy. No special options were used to launch JVM.
    Any ideas?

    I'm having a problem with the same symptom: SIGQUIT is ignored. So I ran jstack and got this:
    Error occurred during stack walking:
    sun.jvm.hotspot.debugger.DebuggerException: sun.jvm.hotspot.debugger.DebuggerException: get_thread_regs failed for a lwp
    at sun.jvm.hotspot.debugger.linux.LinuxDebuggerLocal$LinuxDebuggerLocalWorkerThread.execute(LinuxDebuggerLocal.java:134)
    at sun.jvm.hotspot.debugger.linux.LinuxDebuggerLocal.getThreadIntegerRegisterSet(LinuxDebuggerLocal.java:437)
    at sun.jvm.hotspot.debugger.linux.LinuxThread.getContext(LinuxThread.java:48)
    at sun.jvm.hotspot.runtime.linux_x86.LinuxX86JavaThreadPDAccess.getCurrentFrameGuess(LinuxX86JavaThreadPDAccess.java:75)
    at sun.jvm.hotspot.runtime.JavaThread.getCurrentFrameGuess(JavaThread.java:252)
    at sun.jvm.hotspot.runtime.JavaThread.getLastJavaVFrameDbg(JavaThread.java:211)
    at sun.jvm.hotspot.tools.StackTrace.run(StackTrace.java:42)
    at sun.jvm.hotspot.tools.JStack.run(JStack.java:41)
    at sun.jvm.hotspot.tools.Tool.start(Tool.java:204)
    at sun.jvm.hotspot.tools.JStack.main(JStack.java:58)
    Caused by: sun.jvm.hotspot.debugger.DebuggerException: get_thread_regs failed for a lwp
    at sun.jvm.hotspot.debugger.linux.LinuxDebuggerLocal.getThreadIntegerRegisterSet0(Native Method)
    at sun.jvm.hotspot.debugger.linux.LinuxDebuggerLocal.access$800(LinuxDebuggerLocal.java:34)
    at sun.jvm.hotspot.debugger.linux.LinuxDebuggerLocal$1GetThreadIntegerRegisterSetTask.doit(LinuxDebuggerLocal.java:431)
    at sun.jvm.hotspot.debugger.linux.LinuxDebuggerLocal$LinuxDebuggerLocalWorkerThread.run(LinuxDebuggerLocal.java:109)
    Any ideas/suggestions? Anyone seen this before?

  • Killing child process, not just the shell

    Killing child process, not just the shell
    #241 - 07/11/03 11:30 AM
    Edit post Edit Reply to this post Reply Reply to this post Quote
    Hi,
    I am working on a system for automatically testing student submissions on an introductory course about unix scripting. The program works by running a test script on a student submission, using Runtime.getRuntime().exec(). The Process object has a limited life span of 10 seconds (by default), and if it is still running after these 10 seconds, Process.destroy() is used to kill it.
    A bug exists when one of the submissions being tested times out. When the destroy() method is used it leaves a child process running... since students can also run
    some tests from the file submission client, the number of hanging processes soon adds up as they test and test again to get it right before submission. Eventually this results in too many processes and the server keels over.
    Does anyone have any ideas on killing these hanging processes?

    Not much help, but I think this is a known bug ...
    http://developer.java.sun.com/developer/bugParade/bugs/4770092.html

Maybe you are looking for

  • Scenario IDoc-XI-FlatFile

    Hi, I am trying to Push Idoc from SAP R/34.7 to Flat File thru XI.Message Type is HRMD_ABA.The Idoc is forwarding successfully from SAP R/3,But I am not able see the details and Idoc in XI at all even though in sxmb_moni as well as at Message Display

  • Connecting a 3G ipod to a windows machine

    h i have a 3G ipod and was wondering if i wanted to connect to a windows machine and wanted it to charge at the same time could i use the USB cable or do i have to get the cable that is split into USB and firewire. thanks for all the help

  • By default one field should be greyed out( not input field)

    hi all, My requirement is By default one field should be greyed out( not input field) when i click on a check box and press enter this field should be open to put input values. can some somebody please give me sample code for both PBO and PAI

  • LOV button

    Hi all experts, I attach an LOV to an item, an set the LOV automatic position to YES. When I navigate to that item, the LOV button does not appear. So I can't press the button and select value. I then set the LOV automatic display to YES. When I navi

  • WLS Discoverer Plus fails to connect to database

    I have Discoverer (server) running on a WebLogic Server but cannot get it to connect to my database. IE7 shows a page error in the lower left-hand corner when trying to connect from the Discoverer Plus login page. Displaying the page error shows a me