Runtime.exec() hangs with 1.4.1

Hello altogether,
I am trying to execute a command with Runtime.getRuntime.exec()
I have already taken care of capturing the output and I observe that depending of the program I try to execute the process hangs.
I am using JRE 1.4.1_02 under Redhat 7.2 with kernel 2.4.18-26
Executing the same program under JRE 1.3.1 the program does not hang.
Executing 'top -bn0q' hangs, executing 'ls -als' it hangs.
Here is my sample code:
<code>
import java.io.*;
public class Exec
/** catches the output in a parallel thread */
class StreamReader extends Thread
String category = null;
InputStream is;
StreamReader(String category, InputStream is)
this.category = category;
this.is = is;
public void run()
try
System.out.println(this.category+": reader runs");
InputStreamReader isr = new InputStreamReader(this.is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while (br.ready() && (line = br.readLine())!=null)
System.out.println(this.category+':'+line);
catch (Exception e)
e.printStackTrace();
public void run(String[] cmd)
StringBuffer outStrBuf = new StringBuffer();
try
Runtime rt = Runtime.getRuntime();
System.out.println("got runtime");
Process process = rt.exec(cmd);
System.out.println("fired cmd");
// any errors
System.out.println("prepare error stream");
StreamReader errSr = new StreamReader("ERR",process.getErrorStream());
// any output
System.out.println("prepare output stream");
StreamReader outSr = new StreamReader("OUT",process.getInputStream());
// start the readers to read
System.out.println("start readers");
errSr.start();
outSr.start();
System.out.println("waiting for process to end");
process.waitFor(); //Waits for the subprocess to complete.
catch (Exception e)
System.err.println("Error while executing cmd: " + cmd);
e.printStackTrace();
System.out.println(outStrBuf);
     public static void main(String[] args)
String [] cmd = {"top","-bn0q"};
if (args.length >= 1)
cmd = args;
System.out.println(args[0]);
Exec exec = new Exec();
exec.run(cmd);
</code>
The output of java Exec is:
[user]$ java Exec
got runtime
fired cmd
prepare error stream
prepare output stream
start readers
waiting for process to end
OUT: reader runs
ERR: reader runs
...and there it hangs. Interesting is, that when I use ls -als as command, I get the directory listing.
Do you have any ideas what I am doing wrong? Is there any difference in the Runtime.exec() between 1.3 and 1.4 version?

Unbelievable and what a shame. I was hacking 2 days on several variations of this problem and the solution and I finally found one difference:
while (br.ready() && (line = br.readLine())!=null)
I assume that when executing the command, the output streams are not ready and my Output gobbler threads end.
...however the command is still executing and starts to write its output. And as we all know this will overflow the buffer and the process hangs.
So the final solution is:
/** catches the output in a parallel thread */
class StreamReader extends Thread
  String category = null;
  InputStream is;
  StreamReader(String category, InputStream is)
    this.category = category;
    this.is = is;
  public void run()
    try
      System.out.println(this.category+": reader runs");
      InputStreamReader isr = new InputStreamReader(this.is);
      BufferedReader br = new BufferedReader(isr);
      String line = null;
      while (/**br.ready() &&*/ (line = br.readLine())!=null)
        System.out.println(this.category+':'+line);
    catch (Exception e)
      e.printStackTrace();
}So the only question that I have open: Why does this makes no problem with 1.3 but with 1.4 ?

Similar Messages

  • Running java process in a while loop using Runtime.exec() hangs on solaris

    I'm writting a multithreaded application in which I'll be starting multiple instances of "AppStartThread" class (given below). If I start only one instance of "AppStartThread", it is working fine. But if I start more than one instance of "AppStartThread", one of the threads hangs after some time (occasionaly). But other threads are working fine.
    I have the following questions:
    1. Is there any problem with starting a Thread inside another thread?. Here I'm executing the process in a while loop.
    2. Other thing i noticed is the Thread is hanging after completing the process ("java ExecuteProcess"). But the P.waitFor() is not coming out.
    3. Is it bcoz of the same problem as given in Bug ID : 4098442 ?.
    4. Also java 1.2.2 documentation says:
    "Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock. "
    I'm running this on sun Solaris/java 1.2.2 standard edition. If any of you have experienced the same problem please help me out.
    Will the same problem can happen on java 1.2.2 enterprise edition.?
    class AppStartThread implements Runnable
    public void run()
    while(true)
    try
    Process P=Runtime.getRuntime().exec("java ExecuteProcess");
    P.waitFor();
    System.out.println("after executing application.");
    P.destroy();
    P = null;
    System.gc();
    catch(java.io.IOException io)
    System.out.println("Could not execute application - IOException " + io);
    catch(java.lang.InterruptedException ip)
    System.out.println("Could not execute application - InterruptedException" + ip);
    catch (Exception e)
    System.out.println("Could not execute application -" + e.getMessage());

    I'm writting a multithreaded application in which I'll
    be starting multiple instances of "AppStartThread"
    class (given below). If I start only one instance of
    "AppStartThread", it is working fine. But if I start
    more than one instance of "AppStartThread", one of the
    threads hangs after some time (occasionaly). But other
    threads are working fine.
    I have the following questions:
    1. Is there any problem with starting a Thread inside
    another thread?. Here I'm executing the process in a
    while loop.Of course this is OK, as your code is always being run by one thread or another. And no, it doesn't depend on which thread is starting threads.
    2. Other thing i noticed is the Thread is hanging
    after completing the process ("java ExecuteProcess").
    But the P.waitFor() is not coming out.This is a vital clue. Is the process started by the Runtime.exec() actually completing or does the ps command still show that it is running?
    3. Is it bcoz of the same problem as given in Bug ID :
    4098442 ?.
    4. Also java 1.2.2 documentation says:
    "Because some native platforms only provide limited
    ed buffer size for standard input and output streams,
    failure to promptly write the input stream or read the
    output stream of the subprocess may cause the
    subprocess to block, and even deadlock. "These two are really the same thing (4098442 is not really a bug due to the reasons explained in the doc). If the program that you are exec'ing produces very much output, it is possible that the buffers to stdout and stderr are filling preventing your program from continuing. On Windows platforms, this buffer size is quite small (hundreds of characters) while (if I recall) on Solaris it is somewhat larger. However, I have seent his behavior causing problem on Solaris 8 in my own systems.
    I once hit this problem when I was 'sure' that I was emitting no output due to an exception being thrown that I wasn't even aware of - the stack trace was more than enough to fill the output buffer and cause the deadlock.
    You have several options. One, you could replace the System.out and System.err with PrintStream's backed up by (ie. on top of) BufferedOutputStream's that have large buffers (multi-K) that in turn are backed up by the original out and err PrintStream's. You would use System.setErr() and System.setOut() very early (static initializer block) in the startup of your class. The problem is that you are still at the mercy of code that may call flush() on these streams. I suppose you could implement your own FilterOutputStream to eat any flush requests...
    Another solution if you just don't care about the output is to replace System.out and System.err with PrintStreams that write to /dev/nul. This is really easy and efficient.
    The other tried and true approach is to start two threads in the main process each time you start a process. These will simply consume anything that is emitted through the stdout and stderr pipes. These would die when the streams close (i.e. when the process exits). Not pretty, but it works. I'd be worried about the overhead of two additional threads per external process except that processes have such huge overhead (considering you are starting a JVM) that it just won't matter. And it's not like the CPU is going to get hit much.
    If you do this frequently in your program you might consider using a worker thread pool (see Doug Lea's Executor class) to avoid creating a lot of fairly short-lived threads. But this is probably over-optimizing.
    Chuck

  • Runtime.exec hang

    I used Runtime class to run a 3rd party exe. If I just called
    Runtime.exec("3rd.exe whatever"), 3rd.exe would run half way
    then hang. If I called Runtime.exec("start 3rd.exe whatever"),
    3rd.exe would run successfully. However, Runtime.getInputStream
    couldn't receive the output from 3rd.exe.
    Is any way I can get the output from 3rd.exe with "start 3rd.exe
    whatever"?

    Hi,KellanMom :
    I also experienced this problem.
    You should read sth from Process's inputStream,
    outputStream and errorStream.
    You can browse "http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html" to get details.
    Regards.
    Sunway

  • Runtime.exec() hangs on solaris 10, deadlock in soft_delete_session ?

    Hi,
    In my application sometimes Runtime.exec calls hangs for ever.
    The pstack of java process is at the end of the post. It seems like there is a deadlock in soft_delete_session.
    Does anyone know of any java/os patch we can apply to fix this issue?
    I will really appreciate any tips to get over this issue.
    # uname -a
    SunOS thor256 5.10 Generic_120011-14 sun4u sparc SUNW,Sun-Fire-V245
    # /opt/VRTSjre/jre1.5/bin/java -version
    java version "1.5.0_10"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_10-b03)
    Java HotSpot(TM) Server VM (build 1.5.0_10-b03, mixed mode)
    The trace is as follows:
    0xff340408 __lwp_park + 0x10
    0xff339068 mutex_lock_internal + 0x5d0
    0xfb08a2ec soft_delete_session + 0xf0
    0xfb089f90 soft_delete_all_sessions + 0x4c
    0xfb084348 finalize_common + 0x70
    0xfb0844d8 softtoken_fini + 0x44
    0xfb0d8d48 _fini + 0x4
    0xff3c00d0 call_fini + 0xc8
    0xff3ca614 remove_hdl + 0xab8
    0xff3c4d54 dlclose_intn + 0x98
    0xff3c4e68 dlclose + 0x5c
    0xfb3a2b3c pkcs11_slottable_delete + 0x138
    0xfb39d664 pkcs11_fini + 0x4c
    0xff2c0ea0 postforkchild_handler + 0x30
    0xff332c20 fork + 0x140
    0xfe8f8df4 Java_java_lang_UNIXProcess_forkAndExec + 0x7d4
    0xf9226020 0xf9226020 * java.lang.UNIXProcess.forkAndExec(byte[], byte[], int, byte[], int, byte[], boolean, java.io.FileDescriptor, java.io.FileDescriptor, java.io.FileDescriptor) bci:0 (Compiled frame; information may be imprecise)
    0xf92216c4 0xf92216c4 * java.lang.UNIXProcess.(byte[], byte[], int, byte[], int, byte[], boolean) bci:62 line:53 (Compiled frame)
    0xf90fa6b8 0xf90fa6b8 * java.lang.ProcessImpl.start(java.lang.String[], java.util.Map, java.lang.String, boolean) bci:182 line:65 (Compiled frame)
    0xf90fbe0c 0xf90fbe0c * java.lang.ProcessBuilder.start() bci:112 line:451 (Compiled frame)
    0xf921842c 0xf921842c * java.lang.Runtime.exec(java.lang.String[], java.lang.String[], java.io.File) bci:16 line:591 (Compiled frame)
    0xf9005874 * java.lang.Runtime.exec(java.lang.String[]) bci:4 line:464 (Interpreted frame)
    0xf9005874 * TestExec.run() bci:26 line:22 (Interpreted frame)
    0xf9005c2c * java.lang.Thread.run() bci:11 line:595 (Interpreted frame)
    0xf9000218
    0xfecdca88 void JavaCalls::call_helper(JavaValue*,methodHandle*,JavaCallArguments*,Thread*) + 0x5b8
    0xfecf4310 void JavaCalls::call_virtual(JavaValue*,Handle,KlassHandle,symbolHandle,symbolHandle ,Thread*) + 0x18c
    0xfecf416c void thread_entry(JavaThread*,Thread*) + 0x12c
    0xfecf3ff0 void JavaThread::run() + 0x1f4
    0xff02fb30 void*_start(void*) + 0x200
    0xff340368 lwpstart

    Found this information about this problem:
    Bug: http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=6276483
    Info for patch 127111-11: http://sunsolve.sun.com/search/document.do?assetkey=1-21-127111-11-1
    Download page: http://sunsolve.sun.com/show.do?target=patches/zos-s10

  • Runtime.exec command with spaces

    I'm having problems using exec on (unix) commands that take filenames as a parameter - eg chmod.
    The problem is that I've been blessed with some filenames which contain spaces and I can't figure out a way to pass these through.
    The code I'm trying is :
    String fs="/";
    String droot="home";
    String fname="tom test";
    String fullFileName=fs + droot + fs + fname;
    String outlist[] = runCommand("chmod 777 " + fullFileName );
    if fname contains no spaces, then this will work fine, but (as in the example above) if it contains a space, then I get an error (can't find files).
    Any ideas?
    Thanks
    Tom

    The reason that putting quotes around the filename works on the command line is that they affect how the command line interprets them.
    However, Runtime.exec does not intepret the quotes as special characters. If you have a space in an argument, you should use the Runtime.exec method that takes a String[] argument, and place each argument in an array element.

  • Runtime.exec hangs even If I drain output.

    Hi Everyone,
    I'm trying to make a program that would give me access to a command line on a remote server. So what I'm trying to do is use Runtime.exec("cmd") to open a command line, then reading from it and printing to it normally.
    The problem is the same very common problem anyone using exec encounters: it hangs. The thing is, however, I do drain the input and error streams immediately, but it still hangs, and here's a curious thing:
    When I use a BufferedReader and use its readLine() method, it only manages to read the first two lines before it hangs, giving me an output such as this:
    +Microsoft Windows XP [Version 5.1.2600]+
    +(C) Copyright 1985-2001 Microsoft Corp.+
    Of course I placed the System.out.println inside the loop that reads lines, cause if I put it outside the loop, I don't get any output at all because the subprocess hangs before the loop is finished.
    Now if I don't use a buffer, and use the input's stream's read() method, it reads all the way through the output, but hangs at the end where it's supposed to read -1, and never reads it.
    I thought maybe I could bypass that, and break the loop at the last character in the output (the character '>'). Now while this works the first time, sending the output to the client like this:
    +Microsoft Windows XP [Version 5.1.2600]+
    +(C) Copyright 1985-2001 Microsoft Corp.+
    F:\eclipse workspace\RemCommand>
    However it doesn't work after that, when I try to type any command. I send my command to the subprocess normally using a PrintWriter, and then try to read the output, but that fails because apparently the subprocess is still stuck at the -1 from the previous read operation.
    I really don't know what the problem is, is it possible that the read possibly doesn't return -1 at all, maybe returns a different character to signify the end or something, and my loop keeps trying to read or what?
    I'm at my wits end.
    Any help?
    Thanks in advance.

    Here is the code again. Check the somehow improved detection of the default Windows prompt.
    Check the lines in comments that allow you to define your own, perhaps more reliable prompt.
    import java.io.*;
    import java.util.*;
    public class Cmd
      public static void main( String[] args ) throws Exception
        ProcessBuilder pb = new ProcessBuilder( "cmd" );
    //    Map<String, String> env = pb.environment();
    //    env.put( "PROMPT", ".,.,." );
        pb.redirectErrorStream( true );
        Process p = pb.start();
        InputStream is = p.getInputStream();
        OutputStream os = p.getOutputStream();
        PrintWriter pw = new PrintWriter( os, true );
        readToPrompt( is );
        pw.println( "dir" );
        readToPrompt( is );
        pw.println( "ipconfig" );
        readToPrompt( is );
        pw.println( "netstat" );
        readToPrompt( is );
      private static void readToPrompt( InputStream is ) throws IOException
        String s = "";
        for (;;)
          int i = is.read();
          if ( i < 0 )
            System.out.println();
            System.out.println( "EOF" );
            System.exit( 0 );
          s += new String( new byte[] { ( byte )i } ).charAt( 0 );
          if ( s.endsWith( "\r\n" ) )
            System.out.print( s );
            s = "";
    //      if ( s.equals( ".,.,." ) )
          if ( s.length() > 2 && s.charAt( 0 ) >= 'A' && s.charAt( 0 ) <= 'Z' && s.charAt( 1 ) == ':' && s.endsWith( ">" ) )
            System.out.print( s );
            break;
    }Edited by: baftos on Sep 10, 2008 11:27 AM

  • Runtime exec problem with command "start"

    L.S,
    I'm working on a webservice client for uploading
    and downloading files. When a file is downloaded, it
    should be opened by the appropriate application. I
    know that this is -in theory- possible by issuing a
    start command through Runtime.getRuntime.exec():
    public void doSomething(String realName, DataHandler handler) {
      File outFile = new File(realName);
      FileOutputStream out = new FileOutputStream(outFile);
      handler.writeTo(out);
      out.close();
      String fileName = outFile.getAbsolutePath();
      Process p = Runtime.getRuntime().exec("start " + fileName);
    }Running this on my Win2000 system with J2RE 1.4.2 consistently
    fails with this message:
    java.io.IOException: CreateProcess: start C:\tmp\test.pdf error=2When I issue the exact same command from a DOS shell, Adobe
    starts up with the test document loaded. I now believe that my own
    application is somehow 'holding on to' the file, preventing an
    external application like Adobe from consuming the same file.
    Does anyone know how I can get around a problem like this? How do
    I start the appropriate application and feed it the file that was
    just downloaded by the user?

    I did a search for Runtime.exec and found some good help in this forum. Someone posted something like the following and it works pretty well.
    <<begin code>
    // Determine proper shell command (extend per OS)
    String os_name = System.getProperty("os.name");
    String shellParam "";
    if (os_name.startsWith("Windows"))
    if ( (System.getProperty("os.name").endsWith("NT")) ||
    (System.getProperty("os.name").endsWith("2000")) ||
    (System.getProperty("os.name").endsWith("XP")) )
    shell = "cmd.exe";
    } else
    shell = "command.com";
    shellParam = "/C";
    // Create a string with your program executable
    String command = "myprogram.exe";
    // Create an array of each command, I found that placing "cmd.exe /c"
    // in the same string doesn't work.
    String[] cmd_array = new String[] {
    shell,
    shellParam,
    command
    Runtime.getRuntime().exec( cmd_array );
    <<end code>>
    Do a java API search for Runtime.exec (if you use Eclipse right click and hit Open Declaration) there are ways to invoke exec that support setting of the environment as well as the current directory.

  • Runtime.exec() problem with Linux

    Hi All,
    I have a java program which I am using to launch java programs on all platforms.
    I am using the Runtime.exec() method to start the process in a separate JVM.
    But, I had a problem with the -classpath switch if the directories contained spaces. So I modified the java command which I am passing to the exec() method to something like:
    java -classpath \"./my dir with spaces\" com.harshal.MainThis I had to do because of the problem in windows. But, if I use double quotes in Linux (for the classpath switch in my exec() method), it won't work.
    Can anyone correct me so that I can use the Runtime.exec() method on all platforms to launch the java application even if the classpath directories contains spaces.
    Thank you very much.

    I was reading about the command line args on java's
    tutorial and I found a shocking news. Mac OS doesn't
    support command line args, That's news to me. Could you please elaborate ?
    More important is: I got it working. I figured out I had forgotten to try something before, or, to be more correct, I made an error when trying malcommc's envp suggestion: I used "classpath" as key, not "CLASSPATH", as it should have been.
    Ran a new test, got it working.
    Sample:
    Given a rootdir. Subdirectory "cp test" with a classfile (named "test") without package declaration. Running another class in another directory, using:
    String[] cmd = new String[]{
        "java", "test"
    String[] envp = new String[]{
        "CLASSPATH=rootdir:rootdir/cp test" // <-- without quotes.
    Runtime.getRuntime().exec(cmd, envp);It's been my wrong all the time. I didn't check hard enough. It simply had to work somehow (that's the kind of things that's easy to say afterwards :-)).

  • Runtime.exec Problem with setting environment

    Hello
    I will run a command with a new process environment. As example I take "ls". If I use the "exec(String)" method it works fine (like it should; my PATH is ...:/usr/bin:...).
    Next when I use "exec(String cmd, String[] env)" with cmd = ls and env = {PATH=} then the programm also prints out the listing of the current directory. In my opinion this shoudn't work.
    I have the problem using jdk1.2.2 (Solaris VM (build olaris_JDK_1.2.2_10, native threads, sunwjit)) on Solaris 8.
    As I understand the exec the method should work like this:
    1. fork a new Process
    2 set environment for the new process
    3 exec the new Programm in this process
    Is this statement right?
    On Solaris 2.6 the program works fine and I get an IOException.
    Some hints way the env for the process isn't set?
    Thanks
    ========================================================
    import java.io.*;
    public class Test {
    /** Version der Klasse. */
    public static final String VERSION = "$Revision:$";
    public static void main(String[] arg) {
    try {
    call("ls", new String[]{"PATH="});
    } catch (Exception ex) {
    System.out.println(ex);
    private static void call(String cmd, String[] env)
    throws Exception
    Runtime rt = Runtime.getRuntime();
    try {
    System.out.println(cmd);
    Process p = rt.exec(cmd, env);
    StreamGobbler errorGobbler = new
    StreamGobbler(p.getErrorStream(), "ERROR", System.err);
    StreamGobbler outputGobbler = new
    StreamGobbler(p.getInputStream(), "OUTPUT", System.out);
    errorGobbler.start();
    outputGobbler.start();
    try {
    p.waitFor();
    } catch (InterruptedException e) {
    if (p.exitValue() != 0) {
    throw new Exception("Process failed");
    } catch (IOException ex) {
    System.out.println("IOException: " + ex.toString());
    class StreamGobbler extends Thread {
    private InputStream m_input;
    private OutputStream m_output;
    private String m_type;
    private StringBuffer m_message;
    StreamGobbler(InputStream is, String type, OutputStream os) {
    this.m_input = is;
    this.m_output = os;
    this.m_type = type;
    this.m_message = new StringBuffer();
    outputGobbler.start();
    try {
    p.waitFor();
    } catch (InterruptedException e) {
    if (p.exitValue() != 0) {
    throw new Exception("Process failed");
    } catch (IOException ex) {
    System.out.println("IOException: " + ex.toString());
    class StreamGobbler extends Thread {
    private InputStream m_input;
    private OutputStream m_output;
    private String m_type;
    private StringBuffer m_message;
    StreamGobbler(InputStream is, String type, OutputStream os) {
    this.m_input = is;
    this.m_output = os;
    this.m_type = type;
    this.m_message = new StringBuffer();
    public synchronized void run() {
    try {
    InputStreamReader reader = new InputStreamReader(m_input);
    BufferedReader bufferedReader = new BufferedReader(reader);
    PrintWriter writer = new PrintWriter(m_output, true);
    String line = null;
    while ( (line = bufferedReader.readLine()) != null) {
    writer.println(m_type + "> " + line);
    this.m_message.append(m_type + "> " + line + "\r\n");
    } catch (IOException ioe) {
    ioe.printStackTrace();
    public synchronized String getMessage() {
    return this.m_message.toString();

    I'm having the same problem...
    Have you been able to solve your problem yet?

  • Runtime.exec executed with startup.bat,not executed by service with tomcat

    Using tomcat:
    I startup tomcat ,Start my application through web,and my application called
    Runtime.getRuntime().exec(cmd) successfully.
    But I install a service of tomcat,start service, the same application can't call
    Runtime.getRuntime().exec(cmd) ok.
    who knows this problem?
    thanks.
    auth

    Have you found a solution to this problem?
    I have the exact same issue. Any help would be greatly appreciated.

  • Runtime.exec - hangs or doesn't produce output

    Hey,
    I've been trying to get my program to run an application that I downloaded off the net. It is a console based telnet application build for windows. Now, I've been trying to bascially automate some telnet stuff but it doesn't seem to work at the moment that is it doesn't give me output and it causes my computer to slow down. I've noticed that it does start the application which causes the slow down but I was wondering why it doesn't give me any output. Here is the code that I have
    import java.io.*;
    public class Main
      public static void main(String[] args)
        String command = new String[3];
        command[0] = "cmd.exe";
        command[1] = "/C";
        command[2] = "D:\\Temp\\telnet\telnet.exe";
        try
          Process p = Runtime.getRuntime().exec(command);
          BufferdReader stdin = new BufferedReader(new InputStreamReader
                                                   (p.getInputStream()));
          BufferedReader stderr = new BufferedRader(new InputStreamReader
                                                   (p.getErrorStream()));
          PrintStream stdout = new PrintStream(p.getOutputStream());
          String line = "";
          while((line = stderr.readLine()) != null)
            System.out.println(line);
          System.out.println();
          while((line = stdin.readLine()) != null)
            System.out.println(line);
          p.destroy();
        catch(Exception ex)
          System.out.println("Exception: " + ex.getMessage());
          System.exit(-1);
    }Could some please help me and trying to get this program to work?
    Thanks,
    Ny

    now try it
    you should get
    D:\Temp\telnet' is not recognized as an internal or external command,
    operable program or batch file.
    as an output
    import java.io.*;
    public class Main{
      public static void main(String[] args)
        String[] command = new String[3];
        command[0] = "cmd.exe";
        command[1] = "/C";
        command[2] = "D:\\Temp\\telnet\telnet.exe";
        try
          Process p = Runtime.getRuntime().exec(command);
          BufferedReader stdin = new BufferedReader(new InputStreamReader
                                                   (p.getInputStream()));
          BufferedReader stderr = new BufferedReader(new InputStreamReader
                                                   (p.getErrorStream()));
          PrintStream stdout = new PrintStream(p.getOutputStream());
          String line = "";
          while((line = stderr.readLine()) != null)
            System.out.println(line);
          System.out.println();
          while((line = stdin.readLine()) != null)
            System.out.println(line);
          p.destroy();
        catch(Exception ex)
          System.out.println("Exception: " + ex.getMessage());
          System.exit(-1);
    }

  • Runtime.exec() hangs

    When i am trying to execute a particular dos program from my java program, the system hangs. I am not even trying to retrieve any output from the program in my java code. Executing the same program from the dos shell doesn't cause any problems.
    I am running on Win98 --- hitting CTRL-ALT-DEL tells me that "winoldap" is NOT RESPONDING ---- i don't know what this is (atleast not the name of the program i am executing)
    PLEASE HELP.

    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • The Runtime.exec methods doesn't work well on Solaris ???

    I have two threads and I set the different running time.
    I use Runtime.exec to a run the command and use Process to get the process.
    It works properly in the windows2000 platform.
    However, when I transfer the platform to Solaris...and run the program...
    Two threads always at the same time....It is very wired....I always debug
    for 2 days....
    (at first I run "vmstat 1 2" command, later I change to "ls","rmdir"....etc,
    all of them don't work.....
    If I close the Runtime.exec..........Everything works well......)
    And I study the API. I found this message...
    The Runtime.exec methods may not work well for special processes on certain
    native platforms, such as native windowing processes, daemon processes,
    Win16/DOS processes on Win32, or shell scripts. The created subprocess does
    not have its own terminal or console.
    Could someone share her/his experience.....:(
    And if any other way I can run command inside java code instead of
    Runtime.exec.....???
    Please reply my mail to [email protected] I do appreciate your kindly &
    great help!!!!!!!!
    This is my code.......
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    * <p>ServerThread1</p>
    * <p>??�X???��?�D???�X???, "Vmstat 1 2".</p>
    class ServerThread1 extends Thread{
    private ServerAgent Sa;
    public ServerThread1 (String Name, ServerAgent Sa){
    super(Name);
    this.Sa = Sa; file://Assign ServerAgent reference Sa
    public void run(){
    while(true){
    try{
    Thread.sleep(5000);
    catch (Exception e){
    System.out.println("ServerThread1 fails");
    System.out.println("Thread1 is running.");
    try {
    Runtime rt1 = Runtime.getRuntime();
    Process proc1 = rt1.exec("mkdir"); ------>If I close
    rt1.exec , two threads works seperately...........:(
    catch (Exception e) {
    System.out.println("Thread1 Error");
    class ServerThread2 extends Thread{
    private ServerAgent Sa;
    public ServerThread2 (String Name, ServerAgent Sa){
    super(Name);
    this.Sa = Sa;
    public void run(){
    while(true){
    try{
    Thread.sleep(15000);
    catch (Exception e){
    System.out.println("ServerThread2 fails");
    System.out.println("Thread2 is running.");
    try {
    Runtime rt2 = Runtime.getRuntime();
    Process proc2 = rt2.exec("vmstat 1 2"); ----->If I don't run
    the rt2.exe, two threads work seperately....
    catch (Exception e) {
    System.out.println("Thread2 Error");
    public class ServerAgent{
    private Vector v1 = new Vector();
    private Vector v2 = new Vector();
    private Hashtable currentData = new Hashtable();
    private static String startUpSwap = null;
    private static String startUpMem = null;
    public static void main(String[] arg) {
    ServerAgent s = new ServerAgent();
    ServerThread1 st1 = new ServerThread1("Thread1",s);
    ServerThread2 st2 = new ServerThread2("Thread2",s);
    st1.start();
    st2.start();

    If I close the Runtime.exec..........Everything works
    well......)You don't empty the output of the command, that blocks the process.
    A citation from
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    Why Runtime.exec() hangs
    The JDK's Javadoc documentation provides the answer to this question:
    Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
    Try out something like this:
    String s;
    try {
       Process myProcess =
       Runtime.getRuntime().exec("ls -l"));
       DataInputStream in = new DataInputStream(
              new BufferedInputStream(myProcess.getInputStream()));
        while ((s = in.readLine()) != null) {
            out.println(s);
    catch (IOException e) {
        out.println("Error: " + e);
    }Another source of trouble under Unix is not having the correct permission for that user that executes the Java VM, which will be the permissions for the spawned subprocess. But this probably not the case, as you see something after exit.
    Regards,
    Marc

  • Problem with runtime.exec().It hangs Up

    Hi all,
    I am having a problem with the runtime.exec method.I am trying to execute linux commands using this method.For most of the commands it works fine.But when i tried to change the user with the su command in linux my program hung up.So please help me to get around this.any help would be highly appreciable..
    I am pasting the code..
    <code>
    Process p=null;
    int ch=0;
    try
    System.out.println("Before executing command");
    String unlock_command="sh changeuser.sh";
    p = Runtime.getRuntime().exec(new String[] {"/bin/sh","-c","su tony"});
    InputStreamReader myIStreamReader = new InputStreamReader(p.getInputStream());
    while ((ch = myIStreamReader.read()) != -1)
    System.out.print((char)ch);
    p.waitFor();
    int p_exitvalue = p.exitValue();
    System.out.println("After executing the command and the exit value = "+p_exitvalue);
    p.destroy();
    catch (IOException anIOException)
    System.out.println(anIOException);
    catch(Exception e)
    e.printStackTrace();
    </code>
    Thanks
    HowRYou

    Hi sabre,
    What you have pointed out is right.But if i change the user as root then it will not ask for a password.Isn't it.Anyway thank you for giving your suggestions.Can yoiu help me more.Waiting for all of your help.I will try to swoitch between different users othere than root by giving the password.So just help me.

  • Runtime.exec() causes app to hang

    Hello all, I'm having an issue with the Runtime.exec() and I'm hoping someone in the forum can shed some light on it for me.
    My application currently includes the capability for my end users to run a variety of reports, all of which are written in SQR (BRIO reporting language). Since my application is in Java ( and all the reports were written for a previous application), I use the Runtime.exec() call to launch the SQR viewer application. The problem I'm having is this: When I run the code below in my development environment (using a front end framework from Oracle (JDeveloper)), everything works fine. When I deploy my application to a jar file, the application runs fine until the code below is called. At this point the application hangs terribly and my CPU usage is maxed out by my app. The process for the report is created but is unable to garner the necessary resources to run because my application is using them all. If I kill my application, the report process then runs as expected.
    Why would the same code run fine in development but not when deployed to a jar file?
    The following is the code in question:
        try {
          Runtime rt = Runtime.getRuntime();
          Process proc = rt.exec(sDrive + "\\SQR6\\SQRW " + sDrive + "\\SQR6\\REPORTS\\" + repName + ".SQT " + sConn + " -RT -FC:\\SPL\\ -C -ZIV");
          InputStream stderr = proc.getErrorStream();
          InputStreamReader isr = new InputStreamReader(stderr);
          BufferedReader br = new BufferedReader(isr);
          String line = null;
          while ( (line = br.readLine()) != null)
            System.out.println(line);
          int exitVal = proc.waitFor();
        catch (Throwable ie)
          ie.printStackTrace();
        }    All thoughts and suggestions are welcomed.
    Thanx in advance,
    eribs4e

    So you either tried adding a reader for stdout, or you're sure that nothing is produced on stdout? And you're sure it's not expecting anything on stdin?
    You say your app runs fine up to that code, and then eats all the CPU right? Sounds like a spin lock. One possibility is that it's something like this: br = bufferedReaderForStdOut;
    while ( (line = br.readLine()) != null)
            System.out.println(line);
    while ((line = br.readLine() == null); Not that I expect that you have precisely that in your code, but I suspect the problem may actually be a spin-lock that precedes the code you've posted. I don't see anything obviously wrong with what you have, so if there's a problem in your code, it's probably in what you haven't shown.

Maybe you are looking for