Kill "runtime.getruntime().exec"-generated processes with control-c?

Hi there,
In my java program I create 2 processes with "runtime.getruntime().exec", but when I stop my java program pressing control-c these 2 processes remains running and I have to kill them using linux command "kill".
How can I program my code in order to kill these 2 processes when stopping my java program with control-c?
I tried next but it didn't work for me:
        try {
final Process proc = Runtime.getRuntime().exec ( "java ControlCProblemDemo" );
Runtime.getRuntime().addShutdownHook(
new Thread(){
public void run(){
proc.destroy();
while ( true );
} catch( IOException ioe ) {
System.err.println( ioe );
}Thank you very much in advance.
Josué

so are you saying proc.destroy() does nothing?
are you sure it's getting executed?
is there an error?
too little info here

Similar Messages

  • Using Runtime.getRuntime().exec(DOS Program) with Windows 2000.

    I am trying to spawn a DOS Program from within Java.
    On Win95/98/ME, I use
    Process     p = Runtime.getRuntime().exec("START /w command.com con /c myDOSProgram.exe");
    This works on these platforms. On Win 2000, I use
    Process     p = Runtime.getRuntime().exec("START /w cmd.exe con /c myDOSProgram.exe");
    It does not work at all.
    I have tried all combinations of using START, cmd.exe, con /c, etc.
    I can spawn a Windows App using
    Process     p = Runtime.getRuntime().exec("windows.exe");
    And it works fine.
    What does it take to spawn a DOS program from Java on the Windows 2000 op sys?

    Hi. I recently wrote a java GUI that calls a DOS program with mixed success. Here's the code I used to make the call:String osName = System.getProperty("os.name" );
    String[] cmd = new String[4];
    if( osName.equals( "Windows 2000" ) || osName.equals( "Windows NT" ) )
         cmd[0] = "cmd.exe";
         cmd[1] = "/C" ;
         cmd[2] = "VBDoc.exe";
         cmd[3] = fileName;
    else if( osName.equals( "Windows 95" ) || osName.equals( "Windows 98" ) )
         cmd[0] = "command.com" ;
         cmd[1] = "/C" ;
         cmd[2] = "VBDoc.exe";
         cmd[3] = fileName;
    else
         System.out.println(osName);
    Process proc = runtime.exec(cmd);Check out this article, it gives a good explanation of how to use the exec() call:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    Hope this helps!

  • Runtime.getRuntime().exec problems running with applet

    Hi,
    I am running the command
    Process prc = Runtime.getRuntime().exec("net config workstation");
    InputStream in = prc.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    line = br.readLine();
    When running from an application(/stand alone program) on Win-NT it runs fine. But when i include the same code in an Applet and try to run.
    It doesnt return any thing. I see the DOS-prompt open and close and i can also see the required output generated on the DOS prompt, but the program doesnt return any results(null) in the InputStream.
    I even tried to get the ErrorStream incase it is writing some error but it doesnt write anything.
    I tried running some other commands like (cmd.exe /c set) which were able to run on both application as well as from the applet.
    I have tried giving the "net config workstation" command in all flavors
         String[] cmd = new String[3];
         cmd[0] = "cmd.exe";
         cmd[1] = "/C";
         cmd[2] = "net config workstation";     
    And      
         String[] cmd = new String[3];
         cmd[0] = "net.exe";
         cmd[1] = "config";
         cmd[2] = "workstation";          
    AND
         String[] cmd = new String[5];
         cmd[0] = "cmd.exe";
         cmd[1] = "/C";
         cmd[2] = "net.exe";
         cmd[3] = "config";
         cmd[4] = "workstation";     
    AND giing the full path as
    C:\winnt\system32\net.exe config workstation
    But still it doesnt work.
    Can anybody please suggest what is the problem.Its Urgent.....
    Well the purpose of this is to get users system properties like the Logon Domain , server name etc.... or else can anybody suggest a better way to obtain this information.....
    Your reply will be highly appriciated...
    Thanks in Advance......

    Thanks for atleast replying.....
    Sorry, i forgot to mention.... yes OfCourse, i am using an Signed Applet..... That how i was able to run the "set" command.....
    I have made sure it is not sucha simple problem..... the thing is as i have mentioned i know that even "net config workstation" works..... cause i see the output on the DOS prompt,.... but this output is not returned to the Applet in the getInputStream()/getErrorStream().....
    Can anybody please suggest a way to get this output..... OR is there some other way to get the machine's domain, server name etc info from the machine....?????
    Thanks in Advance...!!

  • Runtime.getRuntime().exec() - native process

    Hi,
    I want to start a native (openFt) program from within my servlet. Therefore, I use Runtime.getRuntime().exec(String [] cmd). This works fine in my local OC4J container: the process is terminated with error code 0 and the native program is executed. The only strange thing here is that the output text isn't in my InputStream but in my ErrorStream.
    The real problem arises when I deploy the same Ear on the 9ias server. Here, the process doesn't execute my native command, terminates with error code 128 and leaves no inputStream and no errorStream.
    Errorcode 128 means that there are no child processes to wait for. (i call process.waitFor() to obtain the error code). I think this means my process isn't even started.
    Anyone familiar with processes in OC4J & 9IAS?
    Thanx in advance

    I guess your implementation of matchIp() is wrong:
    public class ReaderTest {
        public static void main(String[] args) {
            new ReaderTest().testReaderMethod();
        private void testReaderMethod() {
            ByteArrayInputStream dummyStrem = new ByteArrayInputStream(
                    ("*******************************************\n"
                            + "*   My shell Application                   *\n"
                            + "\n"
                            + "*******************************************\n"
                            + "\n" + " \n" + "\n" + "HELP: h\n" + "\n"
                            + "COMMAND: c\n" + "\n" + "QUIT:q\n" + "\n"
                            + "135.19.45.18> ").getBytes());
            System.out.println(readUntilIpMatch(dummyStrem));
        private StringBuilder buffer = new StringBuilder();
        protected String readUntilIpMatch(final InputStream in) {
            while (true) {
                try {
                    if (in.available() > 0) {
                        buffer.append((char) in.read());
                        Pattern pattern = Pattern
                                .compile("\\d{1,3}(\\.\\d{1,3}){3}(?=\\D)");
                        Matcher matcher = pattern.matcher(buffer);
                        if (matcher.find()) {
                            return matcher.group();
                } catch (final IOException e) {
                    throw new RuntimeException(
                            "Failed to read buffer in while looking for prompt!", e);
        } // runs forever if not matching!!!!
    bye
    TPD

  • Runtime.getRuntime.exec() not working with through Servlet

    Hi ,
    I want to open a IE from servlet,I am using a Runtime.getRuntime.exec to open the browser ,but my servlet is executing but IE is not opening...Here i am using TomcatServer...Is any settings to be Done in TomcatServer.
    My Servlet code is
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException
         String s1 = "C:/Program Files/Internet Explorer/IEXPLORE.EXE";
         String s2 = "http://192.168.0.149:8080/etk/etk3.htm";
         Runtime runtime = Runtime.getRuntime();
         runtime.exec(s1 + " " + s2);
    i know it is contrary to the purpose servlets are meant for.but i am using for different purpose..
    help me on this one...
    Thanks in Advance

    No, I am using the right path, I am sure. Also I tried giving the absolute path of the UserGuide.pdf. Still it cannot find. Please anyone try spawning an application from a different directory and lemme know your openion.
    Regards,
    Thomas.

  • Using Process Runtime.getRuntime().exec

    http://im1.shutterfly.com/procserv/47b4d633b3127cceb46774c84ee80000001610
    Here is a URL to a part of the current process I need to run. Actually there are 4 steps that preceed these but they are ran in order and must be done before these (that part is easy). Sorry it kinda chopped off the left side a little bit.
    My question is, can I do this entirely using Runtime.getRuntime().exec() commands or do I need to involve multi threading. The reason I am asking is because P13 cannot run until P8 and P9 completes, but that shouldn't stop the rest of the program from running.
    If I have something like
    Process P4 = Runtime.getRuntime().exec(P4);
    Process P5 = Runtime.getRuntime().exec(P2);
    // Some handling for the streams of these processes goes here
    P4.waitFor();
    P2.waitFor();
    if(P2.exitValue() != 0){
    Process P5 = Runtime.getRuntime().exec(P5);
    Process P6 = Runtime.getRuntime().exec(P6);
    // Some handling for the streams of these processes goes here
    Does that mean the whole program will stop and wait until P4 is done before even checking for P2? If P2 is finished would the program continue and run P5 and P6 even if P4 is still running or will it wait for P4 to complete also. P4 has nothing to do with P2?
    Also any advice ???

    P4 and P2 will both be running in parallel (or as much as your OS and hardware allows them to be). As soon as both are done, and regardless of which finishes first, whatever follows P2.waitFor() will execute.
    If you have multiple groups of processes, where the processes within a group must execute sequentially, but the groups themselves can run independently of each other, then you'll need to either use Java's threads, or wrap each group of sequential processes in a shell script or batch file the executes that group sequentially.
    If there are complex dependencies among the groups--that is, multiple groups must wait on the same process, or one group must wait for multiple other groups, then it might be easier to control the concurrency in Java.

  • Opening a new browser using Runtime.getRuntime().exec(cmd); under windows

    Can Runtime.getRuntime().exec(cmd); open a URL in to a new browser in wondows OS or ...can we force it to any specific browser insted on OS's default browser...
    It does open a new bowser under MAC but not under windows..
    cmd = "'rundll32 url.dll,FileProtocolHandler"+URL (windows)
    Thanks

    public class WindowsProcess
         public static void main(String[] args)
              throws Exception
              String[] cmd = new String[3];
              cmd[0] = "cmd.exe";
              cmd[1] = "/C";
              cmd[2] = "start";
              Process process = Runtime.getRuntime().exec( cmd );
              process = Runtime.getRuntime().exec( cmd );
    }When you run the above code you should get two open dos windows.
    Now just just enter some html filename and hit enter in each window. IE should start up separately in each window.
    Thats also what should happen if you specify the html file as the fourth parameter. A new process should be created and two separate windows should open with a browser in each.

  • Process via Runtime.getRuntime().exec(), how to identify that it�s closed?

    A process(console program) is started via Runtime.getRuntime().exec() from Swing Application.
    Swing Application need to know the result of this process.
    So, is there any possibility to find whether the console program is finished?

    Runtime.exec() returns a Process object.
    Look at its methods, especially waitFor(). Read carefully the whole Process documentation, especially what has to be done with the output streams.

  • Runtime.getRuntime().exec problem with linux script.

    Hello,
    I try to start a script under Linux RedHat 9. This script must just create another file.
    I work with JDK 1.4.1_02b06.
    If I use the next command
    process = Runtime.getRuntime().exec("/temp/myScript.sh");
    This is not working. I script file is existing otherwise I receive an error. I don't understand why the script is not executed!
    I have check some other posts in this forum but I cannot find the solution.
    Thanks in advance for your help.
    Alain.

    Try running it with sh: Runtime.getRuntime().exec("sh /temp/myScript.sh");

  • Need help on changing directories with Runtime.getRuntime().exec() (shell)

    I want to create a perfect remote shell with Runtime.getRuntime(). I just can't get it to change directories. I want that if the remote user type "cd.." he changes the directory. At the moment, I can't get anything else than the "user.dir" directory.
    Is there anyway to send additionnal commands to cmd.exe after the Runtime.getRuntime().exec(). Because at the moment I'm running these commands:
    cmd[0] = "cmd.exe" ;
    cmd[1] = "/C" ;
    cmd[2] = commandString;
    After that I just wanna do stuff as if I really was at the computer and had a cmd.exe window open. I tried the output stream, I tried placing "&&" in front of the commandString(worked when I did it in cmd window), tried doing multiple Runtime.getRuntime().exec(). Starting to pull my hair out here.

    Because essentially I want this to be a remote shell.
    So I need it to accepts commands such as cd to change
    around the directory so the person can navigate the
    computer.
    I just managed to be able to do it in one command
    line. For example I would send "cd c:\downloads dir"
    to the server and it would work but I would really
    like to keep track of the working directory so the
    user wouldn't always have to change the directory.Then you don't Runtime.exec() once for each command the user types. You Runtime.exec() a shell once, and pass what the user types and the shell's responses via the in/out streams available from the Process class.

  • Need help with Runtime.getRuntime().exec

    If there is a better place to post please let me know. I need some help understanding what is going on and was hoping someone might be able to provide some information. I would like to use Runtime.getRuntime().exec to copy a file in linux. Here is the code I am using:
    try {
    Process p = Runtime.getRuntime().exec("cp -v foo foo2");
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;
    while ((line = in.readLine()) != null) {
    System.out.println(line);
    } catch (IOException e) {
    e.printStackTrace();
    If I use cp, with the System.out.println(line) I can see that it has copied and of course when I check the command line indeed it has. My problem is that I really need to use the dd command, but I can't see the output that dd displays. It copies the file just fine but I need the output. If someone can provide some explaination or help I would really appreciate it. Thanks.

    By default, dd sends its output to stdout, so any status messages it has go to stderr. Use getErrorStream (double check the docs for the method name) just like you're currently using getInputSTream.

  • Problems with Runtime.getRuntime().exec in Windows 2000

    Hello,
    I have a batch file that I want to run from my java application. My code is the following:
    try {
            Runtime.getRuntime().exec("cmd.exe /c C:\\temp\\shortcut.bat");
    } catch (Exception e) {
         System.out.println(e.getMessage());
    }I was developing on windows XP and it worked just fine. But then I tested it on windows 2000 and it didn't work. The batch file is okay, because if I run the batch file myself it works just fine, even from the command line. I get no errors what so ever, it just doesn't do anything...
    Can somebody help me with this?
    thx in advance

    thank you all so much
    I figured it out... It was a combination of two things that went wrong.
    First one: in my batch file I had:
    cd C:\tempwhich worsk fine in XP, but in it doesn't in 2000. In 2000 it has to be:
    C:
    cd \temp But just changing that wasn't enough, I also needed the "start"
    Now it works just fine on 2000, hopefully it'll still work on xp as well.
    THX!

  • Problem with Runtime.getRuntime().exec

    Hi ,
    i'm using jBuilderX and windows 2000 server . My problem is that i can't
    find why
    in my code it doesn't work this:
    import java.lang.*;
    String command = new String("c:\\testd\\testf.bat"); // testf.bat -
    batch file
    Runtime.getRuntime().exec(command); // it doesn't
    have any effect
    Thanks in advance,

    What's it supposed to do?
    I can definitely help you on this 1, but I'd really like to see your streamoutputs. You can get these from the Process object that is created, but you'll need to add some threaded listeners to get the data.
    Is this possible?

  • Weird behaviour with Runtime.getRuntime.exec() attempting to start IE

    I have developed a sample scheduler that it a web page the user fill in and then create a process schedule by the Timer class. The process starts IE in order to automate data entry normally done by a user. The Java code run well but IE when start from the p = Runtime.getRuntime().exec() class freeze. Is anyone can tell if IE require special setting to run in background?
    Here the Java code but once again it work well but IE freeze and cause the forked process to hang.
    // The schedule task
    public void scheduleTask(Object o) throws ApplicationException {
    ScheduleBean sb = (ScheduleBean)o;
    try {
    Timer timer = new Timer(true);
    RunReslotting rr = new RunReslotting();
    timer.schedule(rr, sb.getSchedulingDate());
    catch(IllegalArgumentException iae) {
    throw new ApplicationException(iae.getMessage());
    catch(IllegalStateException ise) {
    throw new ApplicationException(ise.getMessage());
    public class RunReslotting extends TimerTask {
    protected RunReslotting() {
    public void run() {
    String[] cmdLineParam = transportProfile(2);
    cmdLineParam[0] = "location=" + wr.getLocation();
    cmdLineParam[1] = "loc_class=" + wr.getNewStrategy();
    forkProcess("runie.bat", cmdLineParam);
    private String[] transportProfile(int startAt) {
    envProf = System.getenv();
    profCmd = new String[envProf.size() + startAt];
    itr = envProf.entrySet().iterator();
    int i = startAt;
    while (itr.hasNext()) {
    entry = (Map.Entry)itr.next();
    profCmd[i] = (String)entry.getKey() + "=" + (String)entry.getValue();
    i++;
    return profCmd;
    private void forkProcess(String processName, String[] osParam) throws ApplicationException {
    // Lance un nouveau process
    p = null;
    int i=0;
    try {
    p = Runtime.getRuntime().exec(processName, osParam);
    // Vide les buffers du process pour eviter de geler
    mcError = new MessageCatcher(p.getErrorStream());
    mcOutput = new MessageCatcher(p.getInputStream());
    mcError.start();
    mcOutput.start();
    i = p.waitFor();
    if ( (i != 0) || (mcError.getMessage() != null) || (mcOutput.getMessage() != null) ) {
    System.err.println("*** Process failed RC:" + i + " *** ");
    if (mcOutput.getMessage() != null) {
    System.err.println("Output messages: " + mcOutput.getMessage());
    if (mcError.getMessage() != null) {
    System.err.println("Error messages: " + mcError.getMessage());
    throw new ApplicationException("*** Process failed *** ");
    catch(IOException ioe) {
    throw new ApplicationException(ioe.getMessage());
    catch(InterruptedException ie) {
    throw new ApplicationException(ie.getMessage());
    Any suggestion will be appreciate. I�m working on that scheduler for a while and i'm desperate
    Thanks
    Francis

    This starts IE for me, no problem
    String[] cmd = {"C:\\Program Files\\Internet Explorer\\iexplore.exe"};
    Runtime.getRuntime().exec(cmd);

  • Runtime.getRuntime().exec portability problem

    Hello everyone!
    I've got a problem with running external application (in my case it's pdfLaTeX). The code looks as follows:
    System.out.println(AppConfig.getExeFile() + " " + params); // AppConfig.getExeFile() is a static function that outputs a String object.
    Process p = Runtime.getRuntime().exec(AppConfig.getExeFile() + " " + params); // params is a String object as well.
    p.waitFor();
    // ...On Linux everything works great. System.out.println() outputs the following line:
    /opt/texlive/bin/pdflatex -halt-on-error   -output-directory /tmp   /tmp/tabular.texThe application executes successfully.
    However, I can't get my program to run on Windows. In this case, the generated command looks as follows:
    "C:\Program Files\LaTeX\MiKTeX 2.7\miktex\bin\pdflatex.exe" -halt-on-error   -output-directory C:\DOCUME~1\Roman\USTAWI~1\Temp   C:\DOCUME~1\Roman\USTAWI~1\Temp\tabular.texAfter displaying this line, my application freezes. The child process (pdflatex.exe) is frozen as well. Then I kill both processes.
    Here's the PdfLaTeX's log file after failure:
    {C:/Documents and Settings/All Users/Dane aplikacji/MiKTeX/2.7/pdftex/config/pd
    ftex.map}
    !pdfTeX error:  (file C:/Documents and Settings/All Users/Dane aplikacji/MiKTeX
    /2.7/pdftex/config/pdftex.map): fflush() failed
    ==> Fatal error occurred, no output PDF file produced!and here's how it should look like:
    {C:/Documents and Settings/All Users/Dane aplikacji/MiKTeX/2.7/pdftex/config/pd
    ftex.map}] (tabular.aux) )
    Here is how much of TeX's memory you used:
    202 strings out of 95340
    2116 string characters out of 1183965
    46926 words of memory out of 1500000
    3474 multiletter control sequences out of 110000
    3640 words of font info for 14 fonts, out of 1200000 for 2000
    14 hyphenation exceptions out of 8191
    23i,6n,17p,173b,100s stack positions out of 5000i,500n,10000p,200000b,5000s
    <C:/Program Files/LaTeX/MiKTeX 2.7/fonts/type1/bluesk
    y/cm/cmr10.pfb>
    Output written on tabular.pdf (1 page, 10003 bytes).
    PDF statistics:
    10 PDF objects out of 1000 (max. 8388607)
    0 named destinations out of 1000 (max. 131072)
    1 words of extra memory for PDF output out of 10000 (max. 10000000)I suspected that the problem was caused by presence of spaces in command (I've tried several other solutions such as putting parameters into String[] array, escaping, adding double-quotes, putting the command to the batch file), but when I run my the same command from the command line, everything works fine.
    I believe that I'm making some kind of a stupid mistake because it doesn't look like it's pdfLaTeX's fault.
    Thanks in advance for your hints. Solutions are welcome as well ;-)

    Hi,
    What is probably happening is that the process is being blocked because you are not reading the output.
    This is a common problem with exec.
    Read this article:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    HTH,
    Eugenio Alvarez

Maybe you are looking for

  • Strange behaviour on text insert into a HTML pane

    Hi all, I am trying to fix a problem on inserting a span tag into an existing html page (in an EDITABLE JEditorPane). The behaviour: Assuming the cells in a table (3 rows, 2 columns) are numbered from 1 to 6, with cell one being the top left most, ce

  • Can photo merge be turned off?

    When I have two or more photos open and I want to move them around, everytime I drag one over the other it becomes transparent. This transparency seems to happen once I drag the photo over the ruler but I could be wrong. Once I release the mouse butt

  • Gaps in idvd slideshow playback

    I just burned my slideshow on a disc.  When I played the disc there was a short countdown and pauses (gaps).  I didn't use chapters so how can i make the slideshow play smoothly? randalfromny

  • Where are passwords saved on my comp?

    Where exactly are passwords, user names, and other info the Autofil text uses saved on my computer? How do I access them? What can I do to see them and print them out? I would like to Reset Safari in order to remove cookies but I'm told it will also

  • Extract data off a broken MacBook Pro 15" Retina Display Mid 2012?

    Hi,,, I had a problem with my MacBook Pro 15" Retina Display Mid 2012  - display and something ending with logic being broken = black screen. Since is was over £1000 to fix it, i decided to buy a new Macbook pro with Retina Display 16gb ram, 512gb. N