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

Similar Messages

  • What is the best way to double buffer in this case and how to do it....

    currently I have
    public class Frame1 extends JFrame{
    //inside this class I call up circle class, rectangle class, etc.... to draw
    }I am making a "paint" program, and I have individual classes to handle the paint methods heres an example:
    abstract public class Shape {
        public Shape() {
        public abstract void draw(Graphics g, Color c, int x, int y, int width,int height);
    }and then....
    public class Circle extends Shape{
        public Circle() {
        public void draw(Graphics g, Color c, int oldx, int oldy, int newx, int newy) {
            g.setColor(c);
            g.drawOval(Math.min(oldx, newx), Math.min(oldy, newy), Math.abs(oldx - newx), Math.abs(oldy - newy));
    }There is also a Rectangle class, line class.... etc! So my question to you is the following... what is the best way to implement double buffer in the individual classes? And how to do it?? And also.... the drawings should be kept inside a jPanel.
    Any bit of help is much appreciated Thank you!!

    You don't need to do double-buffering. Swing
    components are double-buffered by default. Just make
    sure you override paintComponent() and not paint().
    And even if you had to, why would there be any
    difference in implementation for your classes whether
    they paint to on- or off-screen graphics?I need to override paintComponent()? what if I don't...
    I am using JBuilder2005 and they automate somethings for me. So thats how they did it when they created the application they did this....
    public class Frame1 extends JFrame{
    /*** all my code here***/
    public class Application1 {
        boolean packFrame = false;
         * Construct and show the application.
        public Application1() {
            Frame1 frame = new Frame1();
            // Validate frames that have preset sizes
            // Pack frames that have useful preferred size info, e.g. from their layout
            if (packFrame) {
                frame.pack();
            } else {
                frame.validate();
            // Center the window
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            Dimension frameSize = frame.getSize();
            if (frameSize.height > screenSize.height) {
                frameSize.height = screenSize.height;
            if (frameSize.width > screenSize.width) {
                frameSize.width = screenSize.width;
            frame.setLocation((screenSize.width - frameSize.width) / 2,
                              (screenSize.height - frameSize.height) / 2);
            frame.setVisible(true);
            try {
                jbInit();
            } catch (Exception ex) {
                ex.printStackTrace();
         * Application entry point.
         * @param args String[]
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.
                                                 getSystemLookAndFeelClassName());
                    } catch (Exception exception) {
                        exception.printStackTrace();
                    new Application1();
        private void jbInit() throws Exception {
    }

  • What is the best way to back-up my entire library, and How??

    I need to back up my library before somethings happens!!  What is the best way to do that?  Also how do you restore it back on your itunes???

    My 2 cents...
    Fast backup for iTunes library  (Windows)
    Grab SyncToy  2.1, a free tool from MS. This can be used to copy your entire iTunes library (& other important data folders) onto another hard drive or network share. You can then use SyncToy periodically to synchronise or echo your library to the backup. A preview will show which files need to be updated giving you a chance to spot unexpected changes and during the run only the new or updated files will be copied saving lots of time.
    If your media is all organised below the main iTunes folder then you should also be able to open the backup library on any system running the same version of iTunes, regardless of the drive letter or path it appears on.
    Step-by-step install guide
    You restore files simply by copying them back to where they are missing from, or copy back the entire folder in the event of a major disaster.
    tt2

  • Best way to extend wireless via airport express and time capsule

    best way to extend wireless via airport express and time capsule
    i live in a two storey house where i use my airport express to create a wireless network in the main floor, and time capsule to extend it in the upper floor, where my room is. i have like 16 mbps in the main floor, and 2-3 mbps in the upper floor after having speediest.
    i used time capsule in the upper floor because i use wireless backup daily and don't want to put internet down while i im doin it and consequently my parent can have internet access in the main floor, am i right? or do i have make just the opposite in order to have a good internet speed?
    secondly, while checking airport express wireless mode on airport utility, there is like 4 different type of radio mode(802 11n bg comp, 802 11n 2.4, 802 11n a comp, 802 11n 5ghz) which i have no idea what they mean
    what do you recommend?
    we have like iphone4, iphone 3g, mbookpro, ipad, ipad 2, samsung tv and a sony vaio laptop in the wireless network
    thank you

    What you have would appear to be working but I can comment how I would redefine your setup.  Note that both Airport Express and Time Capsule can function as wireless base stations so you do have wireless everywhere and at all times — using the Time Capsules for backups doesn’t mean your parents won’t have internet access regardless of the where the base stations are located.
    You appear to have devices to connect to your network that use the 2.4 GHz band with 802.11g such as the iPhone 3G and perhaps the 5 GHz band with 802.11n such as likely the Macbook Pro if it’s a recent model.  The iPhone 4 can use 5 GHz and 802.11n.  Can’t comment on the Sony and Samsung but you can check their specs.
    Now the Time Capsule (if it’s a recent version), can simultaneously supply 2.4 GHz and 5 GHz band signals, but the Airport Express (if it’s recent) can only use one of those bands at one time.  Likely the lowest common denominator for your devices is going to be the 2.4 GHz band since the devices that are capable of using 5 GHZ also support 2.4 GHz.  If you don’t use 5 GHz, you won’t lose much in a two-storey home because likely it’s the 2.4 GHz band is better signal anyway because 5 GHz signals drop off quickly with several walls/floors to penetrate.
    You also didn’t mention if the Airport Express is used to support a printer and/or AirPlay (using iTunes to play on remote speakers via the Airport Express connection) but that might also be a factor in the best location to place the Airport Express.  Although the printer could be switched between the Time Capsule and the Airport Express if needed, only the Airport Express will support your remote speakers.
    Recommend you use the Time Capsule as the Base station.  When using Airport Utility to define the network, after you name your network, etc., select the Wireless tab, check the box “Allow this network to be extended” and set the Radio Mode to "802.11n (802.11b/g compatible)”.
    Using the Airport Utility, click on the Airport Express; after you define the device and network name, select the Wireless tab, define the Wireless Mode as “Extend a Wireless Network” and check the box “Allow wireless clients”. 
    Hope that helps.

  • What is the best way to do a 10.8 reinstall and keep all of my data?

    What is the best way to do a 10.8 reinstall and keep all of my data?

    Boot to the recovery disk and reinstall the os. That said you do have a back up just in case (I trust)?

  • My wife has gave me her old ipad what would be the best way to set up her new ipad and to have my own ID?

    My wife has gave me her old ipad what would be the best way to set up her new ipad and to have my own ID?

    Backup the old iPad first, either to itunes or iCloud.
    Once that is done, setup the new iPad from the backup. Choose the Restore from Backup option when setting up the new iPad.
    iOS: How to back up /  Restore
    http://support.apple.com/kb/ht1766
    When that is done, wipe the old iPad clean and set up as new.
    Settings->General->Reset->Erase all Content and Settings
    You can create a new Apple Id when you set up the iPad again.

  • I am getting pop ups on safari and firefox lately and am worried i may have malware or something now on my computer doing this. What is the best way to check this out for sure and remove it?

    I am getting pop ups on safari and firefox lately and am worried I may have malware or something now on my computer doing this. What is the best way to check this out for sure and remove it?

    Please review the options below to determine which method is best to remove the Adware installed on your computer.
    The Easy, safe, effective method:
    http://www.adwaremedic.com/index.php
    If you are comfortable doing manual file removals use the somewhat more difficult method:
    http://support.apple.com/en-us/HT203987
    Also read the articles below to be more prepared for the next time there is an issue on your computer.
    https://discussions.apple.com/docs/DOC-7471
    https://discussions.apple.com/docs/DOC-8071
    http://www.thesafemac.com/tech-support-scam-pop-ups/

  • What is Customer order Fill rate process and how we calculate that .

    Hi All,
    Please provide me idea of Customer order Fill rate process and how we calculate that .
    Thanks

    Quote
    Originally posted by WarLord
    I like this HD tool. i use it everyday now. the tempture readings are great Hd temp cpu temp and even the system temp nice added feature to the monitoring. And this is an alternative to enabling the SMART in the bios? Thats the way im understanding it. is that right Maesus ?Because i have disabled in bios. She went threw alot of trouble here. thank you  
    Well from my observation, whether SMART is disabled or enabled in the BIOS, SMART is always working within the HDD itself.
    Basically SMART is acting like a blackbox, monitoring and tabulating HDD condition from time to time and its attributes only fully revealable by the manufacturers. SpeedFan's SMART status only displays partial information that is displayable. Some attributes are hidden, ~OR~ the attributes' locations are different from one HDD to another brand, such that some values don't correspond to the attribute meaning at all.
    It is very doubtful to claim that enabling SMART in the BIOS will hog down the performance. Just like a transport bus (yeah real bus that fetch passenger :P ), with or without the black box installed can't help it if the driver wants to speeding. :P

  • HT2693 i am downloading a software update, but at the last moment before it finishes, it says in order to continue, please close the following application: safari, and the application is closed, what do they mean, and what should i do?

    i am downloading a software update, but at the last moment before it finishes, it says in order to continue, please close the following application: safari, and the application is closed, what do they mean, and what should i do?

    You should close safari.

  • Using runtime.exec,process streams

    Hi all,
    I am using runtime.exec to execute a batch file(rmdir /s/q directoryname) which deletes all the files in a certain directory(including subdirectories). However, some of the files are not deleted since they are being used by other processes.
    I have closed all file references but still the batch file says they are being used by other processes. The File.canWrite() method however, returns true for all the files. I have also tried to delete the files using file.delete but it does not work.
    So I have 2 questions.
    1. Can I forcibly delete these files some other way.
    2. If i call a batch file to delete the files and it fails on some files, the command window displays "cannot delete files". How can I write out thse messages into a text file which i can use as a log file.Do I have to use Process.getInputstream()/Process.getInputstream() ? If so, how?
    Thanks for your help.
    Vinny

    I tried the following before but the string i get is always empty, but i can see there are messages in the command window. Please let me now if i am doing something wrong.
    try{
    Process p = rt.exec("cmd.exe /c start deletefiles.bat");
    InputStream ins = p.getInputStream();
    byte[] bytearray = new byte[1024];
    int bytecount;
    String dos_string="";
    BufferedInputStream bis = new BufferedInputStream(ins);
    while ((bytecount = bis.read(bytearray, 0, 1024)) > -1) {
    String str = new String(bytearray,0,bytecount);
    dos_string += str;
    System.out.println("dos string is" +dos_string);
    catch (Exception e) {
    System.out.println("Error: " + e);

  • What is the best way to close a communication session with the FP Server?

    Looking at NI's FieldPoint Demobox.vi example, the session is closed by wiring the FP Refnum out from the FP Create Tag vi for the AI module to the FP Close vi. Is there any difference if the FP Refnum out from any or all of the other FP Create Tags were wired to FP Close vi/vi's? Could the FP Refnum out from the FP Open vi be wired to the FP Close vi? What is the best way to do this?
    Also, as I'm new to FP and I'm conscious that I might swamp this forum with dumb questions, are the any sources of good FP code examples and/or discussions on coding techniques out there beyond the handful of NI's examples?
    Thanks again,
    Niel.

    Niel,
    The FP Open.vi provides a FP Refnum in the form of a data cluster. The cluster contains two elements; a server refnum and a tag refnum. Coming out of the FP Open, only the server refnum has a value, the tag refnum is created when the FP Create Tag.vi is processed. Thus all FP refnums in a process have the same server refnum but different tag refnums. The FP Close.vi uses the server refnum to close the server and ignores the tag refnum so it does not matter which particular refnum was used to close the server. The thing to be careful of is if you close on refnum, you close all refnums. At this point, any reads/writes/advises will result in error 32804 (Invalid IA handle specified).
    Also, please swamp this forum with questions. I am in the process of reviewin
    g the documentation and examples we provide and having a beginner asking questions that do not appear to be covered in our materials gives me an idea of what we are missing. I would ask that you upgrade to FieldPoint Explorer 2.0.4 and use the online help for LabVIEW since that has had some of my modifications added to it (program flow outlines, vi descriptions & use cases).
    Regards, Aaron

  • BUG? Can't exit JVM until native Runtime.exec() process exited.

    Hi,
    Before reporting this as a bug I wanted to hear some opinion.
    The problem :
    I start a win32 native appllication and then I have to close the VM and leaving the process running.
    But inpite any Runtime.exit() or Runtime.halt() call, the vm won't not exit until the proces ends.
    Having seen that there could be some issue with the output stream of the process and the VM I tried to redirect it to a file. But still the same.
    Any opinion?
    Dikran

    You have something else going on.
    The following code exits and leaves the app running...
        public class TTest
            public static void main(String[] args) throws Exception
            Runtime.getRuntime().exec("notepad");
        }

  • Runtime.exec() process executes too fast!

    I'm trying to pipe some data into an external process via Process.getOutputStream(). However, this program can operate with or without reading from stdin.
    Between the time I run Runtime.exec() and the time I can call Process.getOutputStream(), the process has already decided there's no data coming from stdin and exits.
    Is there any way to give a process stdin data before exec'ing?
    thanks in advance
    Ken

    too fast? never heard that complaint before.
    Well, either it waits for something on stdin or not. If it determines that there's no stdin that fast, how does it ever wait, cuz no user would type faster then the JVM would get the ouputstream? I mean, if you run it on the command line manually, does it sit and wait? Cuz if not, it's not taking stdin at all. Or are you referring to arguments from the command-line, in which case you need to pass them in the Runtime.exec() method first.

  • Best way to know correct forecast model - process chain set up with multiple forecast models

    Hi Experts,
    I need your help in selecting best forecast model for our company. We have some of the models already used for our company, and because of multiple models used it is taking very long time for process chain to finish. There is no existing documentation available on which model was used why initially. Please help me to make out forecasting process smooth.
    - What is the best way to know, which forecast model is correct and should be used for our forecasting process.
    - In case multiple forecasting models are really required to be used, please suggest ways to optimally schedule them in process chain.
    - At times we get messages like "not enough data available" for specific model - any way to avoid this.
    - How to optimally use parallel processing profiles forecasting process in process chain.
    - Things which should be avoided.
    Request your help, please share your experiences.
    Regards
    NB

    Hi Neelesh,
    There are many points you need to consider to redesign forecast process for your company/client.
    You need to select the best suited forecast model first depending on the business. This has to be well tested & agreed by business users. Complexity will be an outcome of this exercise with business users. Best id to give then a brief intro on all available models & then help them selection the best one as per their requirement.
    Auto selection models are generally more time taking & should be used only when you have no idea at all on the business/demand pattern.
    Run time will depend how you are clubbing the CVCs to get the forecast generated & also parallel processing. For parallel processing profile you will need to do trial & error testing along with help from Basis team on how many free dial up processes are available.
    Even you can run many forecast calculations in parallel if the product/cvcs are totally different. - As per my personal experience maximum run time reduction can be achieved here.
    Daily run is not advisable except only for businesses where you have too much dynamism in demand planning i.e. you expect the demands to be changed overnight. Most of the companies run forecast on monthly basis or at weekly basis at the max.
    "Not Enough data" will be a problem if you are having the irrelevant models used in forecast profiles. This means users are not bothered to maintain the needed data for he forecast calculations or they are not aware at all of the situation. Running such models on daily basis is not advised at all. Better users should use interactive forecasting & saving the results in such cases.
    Just to give a crude example we get forecast calculated on monthly basis for approximately 4 lac cvcs in less than 3 hrs using moving avg, seasonal linear regression, seasonal trend, croston models. We use parallel profiles also everywhere with 10 blocks & 500 cvc/block.
    Hope this helps. Let me know if you have nay more questions & also the results using any of this.
    Regards,
    Rahul

  • Runtime.exec() process output

    I am having strange problems with the output from a program I am executing with Runtime.exec(). This program takes voice input, and generates text output on the commandline. For some reason, I do not see any of the output until the program exits, then everything is displayed. My code is below, any help would be greatly appreciated!
    Thanks,
    Deena
    import java.io.*;
    import java.util.*;
    //Reads and prints the output streams from an executing process
    class ProcessStream extends Thread{
         InputStream is;
         String type;
         ProcessStream(InputStream is, String type){
         this.is = is;
         this.type = type;     //type of output stream, e.g. stdout or stderr
         public void run(){
         try{
              BufferedReader br = new BufferedReader(new InputStreamReader(is));
              String line=null;
                   //read and display the output stream of an executing process
              while ((line = br.readLine()) != null){
              System.out.println(type + ">" + line);
         } catch (IOException ioe){
         System.err.println(ioe);
    //Interface to TalkBack.exe
    public class JTalkBack{
         public static void main(String[] args){
         try{
              String arg="TalkBack.exe -noTTS -noReplay";     //program to execute
              //arguments to program
              for(int i=0; i<args.length; i++){
                   arg+=" "+args;
              //execute the program and get an object representing the process
              Process p=Runtime.getRuntime().exec(arg);
              //create stream processors for stdout and stderr of the process
              ProcessStream error = new ProcessStream(p.getErrorStream(), "ERROR");
              ProcessStream output = new ProcessStream(p.getInputStream(), "OUTPUT");
              //start the stream processors
              error.start();
              output.start();
              //wait for the process to finish and get its exit value
              int exitVal = p.waitFor();
         System.out.println("ExitValue: " + exitVal);
         catch (Throwable t){
         System.err.println(t);

    I have something similar and it works. The only difference is that I:
    1. used a BufferedInputStream instead of the BufferedReader, which means bis.available() and bis.read(buffer) were used instead of .readLine(bis)
    2. Didn't print to stdout, but instead fired a proprietary MessageEvent with the string in it to all MessageListeners (good for use with java.util.logging)
    3. Didn't (yet) put the input streams in different threads.
    Maybe it is related to the fact that you are printing directly back to the System.out again? Does each process in Java get its very own standard out? I don't know.
    It's ugly and convoluted, but maybe a snippet of my code will help...
    (in run)
    Thread myThread = Thread.currentThread();
      try {
        proc = r.exec("my_secret_process.exe -arg arg");
        is = new BufferedInputStream(proc.getInputStream());
        while (thread == myThread) {
          int iRead = 0; //how many bytes did we read?
          //message stream check
          if(is.available() > 0) {
            iRead = is.read(buf);
            msg = "\n"+new String(buf, 0, iRead);
            this.fireMessageArrived(new MessageEvent(this, msg));
         } //end while
       } catch(Exception e) {
          System.out.println("Argh.  Barf.");
      Tarabyte :)

Maybe you are looking for

  • Brown vs Silva and Stiverne vs Arreola

    A Militant has UFC Conflict Period 40 results for the Brownish vs. Silva press greeting Friday dark at the U.S. Cant Arena in Cincinnati, Ohio. In the main circumstance, Matt Abolitionist will simple off against Erick Forest in a welterweight repugn.

  • Problem using icommand in UNIX

    Hi, I'm trying to use icommand in UNIX. I navigate to the middleware home on the server and in the .../BAM/Bin directory I can see an icommand.bat file and the standard icommand file. However, I can't see an icommand.sh file. I've tried some commands

  • System wide keychain?

    Is there a way to store passwords in some sort of "system-wide" keychain, so that any user that logs into a machine (networked, or local) can have access to it? What I want to do is set up a keychain with the WPA key for all of the airports in my dis

  • AVI Write with Data Problem

    Hi, Im trying to write video and data into an avi file, and I based my program mainly on the AVI read write with data example, however My write does not seem to be writing the data to the avi file. I have a test signal which is converted to a double

  • Bing fault.

    I have a synchronus process which calls a webservice. The webservice is one of the bpel process. The process that calls this webservice errors on the invoke stating BINDING FAULT. <bindingFault> <part name="code" > <code>GenericError</code> </part> <