Running interactive command with Runtime.exec

I'm trying to run a command via the Runtime.exec interface.
Occasionally, the command needs to prompt for additional information. The response depends on the specific configuration, however, the command returns a list of options and then waits for a response.
However, when the command waits for the response, my Java app hangs.
After I call Runtime.exec, I create 2 threads to consume the contents of stderr and stdout. I then start them and call proc.waitFor()
I would expect to see the output of the command in the stdout stream even though the command hasn't exited. I had hoped to parse the output to determine the necessary response. However, the calls to read the contents of the stdout and stderr streams block and I never see any output.
How can I get access to the contents of those streams while the command is still running? Is this supported through the Runtime.exec interface?
Thanks,
Shawn

This article should help:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

Similar Messages

  • Running System commands using Runtime.exec()

    I'm trying to run an example from "The Java Programming Language" book by Arnold, Gosling and Holmes. I'm trying to run a system level command and get the results. The code looks like:
    public static String[] runCommand(String cmd) {
    String[] outputData= null;
    String[] cmdArray = {"/usr/bin/ls", "-l", "/tmp"};
    try {
    Process child = Runtime.getRuntime().exec(cmdArray);
    InputStream in = child.getInputStream();
    InputStreamReader reader = new InputStreamReader(output);
    BufferedReader = new BufferedReader(reader);
    // read the commands output
    int counter = 0;
    String line;
    while ((line = input.readLine()) != null)
    outputData[counter++]= line;
    if (child.waitFor() != 0){  // error when it's not 0       
    System.out.println("Couldn't run the command.");
    System.out.println("It produced the following error message : " + child.exitValue());
    outputData = null;
    } catch (Exception e){
    System.out.println("It got here!");
    System.out.println("It produced the following error message : " + e.getMessage());
    outputData = null;
    return outputData;
    It gets to the while line, trys to run the input.readLine() and kicks out the exception that looks like:
    It got here!
    It produced the following error message : null
    I know it gets to the input.readLine() because I had a whole lot more try blocks in there, but for simplicity left it out (so it look like the code in the book, which I tried originally). When I run the same command from the command line (on our Sun Solaris 2.8 system) I get results back. I'm not sure what I'm doing wrong. Any help would be greatly appreciated. Thanks.

    Hi, duffymo, hope you can help me. Consider this servlet code:
    String theCommand = "csh /export/home/gls03/sasstuff/runsas.csh /export/home/g
    ls03/sasstuff/gary2.sas";
    //Create a parent Process for the sas program subprocess:
    Process p = rt.exec(theCommand);
    System.out.println("after call to rt.exec(theCommand)");
    Here is the runsas.csh script:
    #!/bin/csh
    setenv LD_LIBRARY_PATH /opt/sybase/lib:/usr/lib:/usr/openwin/lib:/opt/SUNWspro/S
    C2.0.1
    setenv SASROOT /usr/local/CDC/SAS_8.2
    setenv XKEYSYMDB /usr/local/CDC/SAS_8.2/X11/resource_files/XKeysymDB
    $SASROOT/sas -sasuser /hpnpages/cgi-bin/applinks/hospcap/tmp $1
    The execution never gets to the println statment, here is the error:
    class java.io.IOException Exception. Message: CreateProcess: csh /export/home/g
    ls03/sasstuff/runsas.csh /export/home/gls03/sasstuff/gary2.sas error=2
    java.io.IOException: CreateProcess: csh /export/home/gls03/sasstuff/runsas.csh /
    export/home/gls03/sasstuff/gary2.sas error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Win32Process.java:66)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:551)
    at java.lang.Runtime.exec(Runtime.java:477)
    at java.lang.Runtime.exec(Runtime.java:443)
    at sasRunnerNew.doPost(sasRunnerNew.java:103)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubIm
    pl.java:262)
    at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:21)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.ja
    va:27)
    at us.ny.state.health.hin.hinutil.HinFilter.doFilter(HinFilter.java:124)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.ja
    va:27)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppSe
    rvletContext.java:2643)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestIm
    pl.java:2359)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:139)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
    The command runs fine in unix.
    I've also tried using these as arguments to exec:
    String theCommand = "/bin/csh /export/home/gls03/sasstuff/runsas.csh /export/home/gls03/sasstuff/gary2.sas";
    String[] theCommand = {"csh", "/export/home/gls03/sasstuff/runsas.csh", "/export/home/gls03/sasstuff/gary2.sas"};
    These generate the same error. I'm thinking this is a sas-specific problem.
    Thanks for any help. Gary

  • Run Linux script with Runtime.exec

    Hi there!
    I want to run some Linux script files out of a Java application.
    I'm currently using a code like this:
    Runtime rt = Runtime.getRuntime();
    Process p=rt.exec("//home//scriptFile1");But this isn't working. Although I'm getting no exeption, the file isn't executed.
    It looks like he's doing something, but he's definitly not processing the file.
    I think the problem is probably, that in scriptFile1, I call some other script files (which call itself some other script files).
    E.g. like this:
    scriptFile1:
    scriptFile2
    binary1
    binary2
    scriptFile3Any ideas?
    Thank you!

    Hi! I now get at least some error messages, when I call the script file:
    knoppix@Knoppix:~/Desktop$ java Main
    start
    ERROR>/media/hda5/scripts/startds_2: line 1: stop: command not found
    ERROR>/media/hda5/scripts/startds_2: line 3: dspp_2: command not found
    ERROR>/media/hda5/scripts/startds_2: line 5: killcan: command not found
    ERROR>/media/hda5/scripts/startds_2: line 7: canpdemsimeit: command not found
    ERROR>/media/hda5/scripts/startds_2: line 9: demsimeit: command not found
    ERROR>/media/hda5/scripts/startds_2: line 11: guidemsimeit: command not found
    ERROR>/media/hda5/scripts/startds_2: line 13: MCAbrowser: command not found
    ExitValue: 0These "lost" commands are all located in the same directory as the script I call, so I wonder why.
    I could adjust every command by adding in front of it the absolute path in the script file. That would work. But maybe I can pass in some other way the directory, in which he should search for the commands. That would save me a lot of work...
    I will RTFM but if anyone has currently an idea: please post...
    THX

  • Problem to execute cvs command using Runtime.exec method

    Hello,
    I want execute this cvs command, with this options:
    cvs -d :pserver:[email protected]:/home/cvs/cvsroot rlog -S -d "2007/05/01<now" Project
    I tried to execute with Runtime.exec() :
    Runtime.exec("cvs -d :pserver:[email protected]:/home/cvs/cvsroot rlog -S -d \"2007/05/01<now\" Project");
    But I have an error because the smaller character is interpretate as a redirection, no as a smaller symbol.
    How I can do to use this command with Runtime.exec ?
    Thanks.
    Regards.

    Sorry,
    I had a typing mistake.
    I want say:
    Runtime.exec("cvs -d :pserver:[email protected]:/home/cvs/cvsroot rlog -S -d \"2007/05/01<now\" Project");
    Regards.

  • Problems with Runtime.exec() and certain Unix processes

    Certain Unix processes don't behave correctly when run from Java using Runtime.exec(). This can be seen by running /bin/sh and trying to interact with it interactively. The issue appears to be that /bin/sh (and many other Unix tools) are checking the file handles on the spawned process to see if they are associated with a TTY.
    Is there any way to associate a process spawned by Runtime.exec() with a terminal or alternatively, is there a JNI library available that would setup the process correctly and still provide access to the input and output streams?
    Our objective is to have the flexibility of expect in being able to run and interact with spawned processes. A bug was opened at one point but closed back in 1997 as being a fault in the spawned process, not Java.
    Bug ID: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4058689

    #include <stdio.h>
    void doit() {
    int c;
            while((c=getc(stdin)) != EOF) {
                    printf("%c",c);
    int main() {
            freopen("/dev/tty", "r", stdin);
            doit();
    }This program reopens its standard input against /dev/tty and catenates it to stdout. And voila, it takes its standard input from the terminal, even though it was started with stdin against /dev/null..
    $ gcc b.c -o b
    $./b < /dev/null
    buon giorno
    buon giorno

  • Killing Internet Browser opened with Runtime.exec

    I am running Win NT 4.0 and I am successfully opening my HTML help using the following code:
    String command = new String("cmd /K ");
    command = command.concat("G:\editor\help\index.html");
    Process p = Runtime.getRuntime().exec(command);
    However, if I run p.destroy(), the browser window does not close. This means that the help remains open after the program exits and also that multiple help windows can be opened.
    Does anyone know how to kill a browser opened with Runtime.exec()?
    Thanks for any help you can offer,
    Christopher Collins
    Marineering Limited

    Thanks jmschrei,
    I tried System.exit(0) and Runtime.getRuntime().exit(0) and neither succeeded in closing the internet browser process. I suspect that process.destroy() and runtime.exit(0) both are killing the instance of the command interpreter spawned by runtime.exec("cmd /K URL") and not actually the browser opened by that command. Therefore, I think that the process refers to the "cmd" and not the browser, which probably opens completely independently of my Java program, thus can't be closed by it.
    Unforetunately, I don't know another way to open a browser.
    If anyone has any additional suggestions, I would appreciate it. Many people in the forums seem to have asked this one, and there are no solutions I could find.
    Christopher

  • Problem with Runtime.exec()

    Hi,
    I'm having a problem with Runtime.exec() . I have a batch file with debug option to FTP the desktop file to mainframe. When I executed this in Windows it's shows me the responce from the server (like ' Transfer Completed' ) for my FTP commands. But when I launch this through java it's only shows the errors not the normal responces from the server. I need this responses to confirm the proper transfer of file.
    My Java Code:
    String strCommand = "cmd.exe /c " + outdirectory + batchfilename;
    boolean bWait = true;
    Runtime r = Runtime.getRuntime();
    Process pr = r.exec(strCommand);
    BufferedInputStream bis =new BufferedInputStream(pr.getInputStream ());
    int c=0;
    /** Outlet for IO for the process **/
    while (c!=-1) {
    c=bis.read();
    /**Now wait for the process to get finished **/
    if(bWait == true){
    pr.waitFor();
    pr.destroy();
    My Batch file is :
    FTP -n -d -s:C:\IT2.cmd > C:\tIT2.log
    EXIT
    Thanks
    Sathiesh

    Ahh, you are redirecting the standard out from the ftp command to a file, therefore no output is sendt back to your java code,
    you have to redirect the stderr stream, not the stdout stream in your batch file;
    FTP -n -d -s:C:\IT2.cmd 2> C:\tIT2.log(notice the "2>" instead of ">")
    Now your batch file should direct the error stream to the log, and the standard output back to the java program.
    (I'm used to UNIX streams, not NT, but the "2>" redirection should work on NT also I guess)

  • Launch Acrobat Reader with Runtime.exec() under WINNT4, without absolut pat

    Hi,
    I would like to launch Acrobat Reader from a Swing application. This works fine with Runtime.exec() as long as I provide the full path to the AcroRd32.exe. The problem is that I cannot predict the location of this exe on the systems of the users. Athough is in the Windows PATH, since I can launch from the windows execute-dialog, the Runtime.exec() is not able to locate the file.
    How can I solve this problem?
    Thanks a lot!
    Horst

    hey BIJ, thank you so much man. start really does wonders!! i was stuck with invoking a fortran program for last couple of days and now i went through your postings and tried with start. it did work!!
    thanks again,
    bhairampally

  • Run os commands with sql

    dear all,
    is it possible to run os commands with sql commands as follows :
    SQL> ALTER system kill session '1764,60569'; ! kill -9 12151
    2 /
    ALTER system kill session '1764,60569'; ! kill -9 12151
    ERROR at line 1:
    ORA-00911: invalid character
    kai
    os version : solaris 5.10.. db : 10.2.0.4.0

    Kais,
    What exact error are you getting running this script and what's OS (is it linux RH?? If you can post errors on running this script, that will be helpful. I tested on both cygwin (my desktop) and liunx box but you can change as needed) and to kill process from script you can use
    echo `kill -9 pid`
    Hope this helps
    #!/bin/bash
    typeset username=$1
    function readSqlstmt {
    typeset stmt=$1
    echo "
    set feedback off
    set verify off
    set heading off
    set pagesize 0
    whenever sqlerror exit 1
    whenever oserror exit 2
    $stmt;
    exit
    " | sqlplus -S '/as sysdba >> test.log
    function killpid {
    killpidsql=killpid.sql
    sqlplus -s '/as sysdba' << ENDOFSQL >> test.log
    whenever sqlerror exit 1
    whenever oserror exit 2
    SET pagesize 0
    SET verify off
    SET feedback off
    SPOOL ${killpidsql}
    SELECT 'ALTER system kill session ''' || s.sid || ',' || s.serial# || ''';'
    FROM v\$session s, v\$process p
    WHERE s.paddr = p.addr AND s.status = 'INACTIVE';
    SPOOL OFF
    @${killpidsql}
    ENDOFSQL
    killpid
    readSqlstmt "SELECT p.spid FROM v\$session s, v\$process p WHERE s.paddr = p.addr AND s.status = 'INACTIVE'" | while read u
    do
         #echo "kill -9" $u >> test.log
         echo "Killing inactive oracle process..."
    echo `kill -9 $u`
    done

  • Launch Command Line Scanner with Runtime.exec()

    Hi im trying to develop all the process of a common Antivirus ,
    I have a command line anti-virus. But when i try to scan a single file mi code doesnt work.
    I made the following code:
    Runtime runtime = Runtime.getRuntime();
    commands = new String[] {"cmd.exe", "/c","C:\\KAVCLineScanner\\kavecscan.exe","C:\\anfed\\a.txt"};
    Process p =runtime.exec(commands);
    BufferedReader b =new BufferedReader(new
    InputStreamReader(p.getInputStream()));
    String line=null;
    while( (line=b.readLine())!=null){
    System.out.println(line);
    I think the problem is my parameter where i send the file to scan "C:\\anfed\\a.txt", because if i execute this instruction from MSDOS, the process doesnt have problems.
    I also made a .bat file with the instructions but i have the same problem :(
    Thanks for any advise

    I think java naming is from programmer's point of view, so the output stream of the process would be the inputstream to the programmer, hence I am trying to write to my outputstream, which is actually the process' inputstream.

  • Need to run two commands in Runtime.getRuntime.exec()???

    I need to run two commands in the same shell , in the same exec function... is this possible? I tried to invoke
    ksh -e ... command1;command2
    but that did nothing

    I need to run two commands in the same shell , in the
    same exec function... is this possible? I tried to
    invoke
    ksh -e ... command1;command2
    but that did nothingI'm not all that familiar with that particular shell (ksh), but if it works from the command-line, I'd venture to guess that it would have worked there as well. My guess is it did "work" (executed the 2 commands) but that you may have misdiagnosed the real problem (current working directory assumption incorrect, etc).

  • Error in opening a file with name in chinese characters with Runtime.exec

    The issue at hand is when I try to open a file with file name containing chinese characters in a localized environment in Windows through the following java code:
    Runtime.exec("rundll32 SHELL32.DLL,ShellExec_RunDLL {File_With_FileName_containing_Chinese_character}");
    the following error is thrown by windows.
    Cannot open file "C:\??.txt".
    with the exception
    java.io.IOException: CreateProcess: [Ljava.lang.String;@f5da06 error=2
            at java.lang.Win32Process.create(Native Method)
            at java.lang.Win32Process.<init>(Win32Process.java:66)
            at java.lang.Runtime.execInternal(Native Method)
            at java.lang.Runtime.exec(Runtime.java:566)
            at java.lang.Runtime.exec(Runtime.java:428)
            at java.lang.Runtime.exec(Runtime.java:364)
            at java.lang.Runtime.exec(Runtime.java:326)
            at Launcher.main(Launcher.java:26)
    When I try to use the same command (shown below) from the Windows Run command, the file opens sucessfully
    rundll32 SHELL32.DLL,ShellExec_RunDLL {File_With_FileName_containing_Chinese_character}
    Please suggest.
    Thanks in advance

    This may be a file association problem.  To solve that:
    In Windows 7:
    1. Right-click the file,
    2. Select "Open With" 
    select [Your Program Here]
    3. Check always use this program. 
    In Windows XP:
    1. Locate the file as you have described above
    2. Right click the file
    3. Select Open with from the pop-up menu
    4. Click Choose default program…
    5. Select Excel in the Recommended Programs box
    6. Check Always use the selected program to open this kind of file
    7. Click on OK.
    1.  Make Excel not available from Office 2007 listed under Programs and Features in Control Panel.
    2. Take a registry backup using the steps given here
    3. In the registry editor window expand HKEY_CLASSES_ROOT and navigate to .xls right and delete it.
    4. Exit Registry Editor
    5. Undo Step 1 to make Excel available.
    6.  Restart the computer and verify it the issue is fixed.
    If this answer solves your problem, please check Mark as Answered. If this answer helps, please click the Vote as Helpful button. Cheers, Shane Devenshire

  • Trying to run external script using Runtime.exec

    Hey,
    I am trying to use Runtime.exec(cmd, evnp, dir) to execute a fortran program and get back its output, however it seems to always be hanging. Here is my code snippet :
                Process process = Runtime.getRuntime().exec(
                      "./fortranCodeName > inputFile.txt" , null, new File("/home/myRunDir/"));
                InputStream stream = new InputStream(process.getInputStream());
                InputStream error = new InputStreamr(process.getErrorStream());
                BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stream));
                BufferedReader erroutReader = new BufferedReader(new InputStreamReader(error));
                System.out.println(stream.available());  //returns 0
                System.out.println(error.available());     //returns 0
                while (true) {
                    String line1 = stdoutReader.readLine();  //hangs here
                    String line2 = erroutReader.readLine();
                    if (line1 == null) {
                        break;
                    System.out.println(line1);
                    System.out.println(line2);
                }I know for a fact that this fortran code prints out stuff when run it in terminal, but I don't know if I have even set up my Runtime.exec statement properly. I think I am clearing out my error and input streams with the whole reader.readLine bit I have above, but I am not sure. If you replace the command with something like "echo helloWorld" or "pwd", it prints out everything properly. I also am fairly confident that I have no environmental variables that are used in the fortran code, as I received it from another computer and haven't set up any in my bash profile.
    Any Ideas?

    Okay, so I implemented the changes from that website (thanks by the way for that link, it helps me understand this a little better). However, my problem is still occuring. Here is my new code:
                class StreamThread extends Thread {
                InputStream is;
                String type;
                StreamThread(InputStream is, String type)
                    this.is = is;
                    this.type = type;
                public void run()
                    try
                        InputStreamReader isr = new InputStreamReader(is); //never gets called
                        BufferedReader br = new BufferedReader(isr);
                        String line=null;
                        while ( (line = br.readLine()) != null)
                            System.out.println(type  +">"+  line);
                        } catch (IOException ioe)
                            ioe.printStackTrace();
            try {
                Process process = Runtime.getRuntime().exec(
                      "./fortranCodeName" , null, new File("/home/myRunDir/"));
                StreamThread stream = new StreamThread(process.getInputStream(), "OUTPUT");
                StreamThread errorStream = new StreamThread(process.getInputStream(), "ERROR");
                stream.start();
                errorStream.start();
                int exitVal = process.waitFor(); //hangs here
                System.out.println("ExitValue: " + exitVal);

  • How to run Unix command with Pipe ( | )?

    Dear Friends,
    I have to execute the below unix command through java program.
    *ps -ewwo pid,args | grep -E "abc.sh|xyz.jar" | gawk '{ print $1 }' | wc -l*
    My code to execute this command is,
    Runtime run = Runtime.getRuntime();
    File workDir = new File("/root/sat");
    String psCmd = "ps -ewwo pid,args | grep -E \"abc.sh|xyz.jar \" | gawk '{ print $1 }' | wc -l";
    Process process = run.exec(psCmd, null, workDir);
              String line;
              int i = process.waitFor() ;
              if(i == 0) {
              BufferedReader buf = new BufferedReader( new InputStreamReader( process.getInputStream() ) ) ;
              while ( ( line = buf.readLine() ) != null )
                   System.out.println("Line - ["+line+"]") ;
              } else {
                   BufferedReader stdErr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                   // read the output from the command
                   while ((line = stdErr.readLine()) != null) {
                   System.out.println(line);
                   }When i execute this command, i'm getting output as,
    ERROR: Garbage option.
    When i analyse the above error, i found that, the PIPE ( | ) command is not supported through java.
    Could anyone please help me how to execute the above unix command (with | ) in java?
    Thanks in advance,
    Sathish

    The pipe has to be interpreted by a shell so you need
    String[] psCmd =
        "sh",
        "-c"
        "ps -ewwo pid,args | grep -E \"abc.sh|xyz.jar \" | gawk '{ print $1 }' | wc -l"
    Process process = run.exec(psCmd, null, workDir);You should also read, re-read and then implement the recommendations in the 4 sections of http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html .

  • Running a command by Runtime class on Unix system

    Hi,
    To run a command in Windows I wrote the following code:
    String s = "cmd.exe /C " + AnyCommand;
    Process p = Runtime.getRuntime( ).exec( s );
    For Unix system, what do I need to replace the "cmd.exe /C"?
    Thank you

    I am not familiar with Unix.
    I've tried "bash", but that diesn't work
    The AnyCommand is a compiling command "javac
    className.java"Well, javac is an executable. So you don't need a command shell around it to run it, unless you want certain things like redirecting standard output to a file, such that the command shell provides. Just pass "javac className.java". (Now next question will be why doesn't it work, because you also have to take into account the current directory from which you launched javac, and so forth)

Maybe you are looking for

  • Solution manager RCA with third party applications

    Hi, Our setup is fairly huge with several third party applications being used. For every business scenario there are 2 or 3 other applications  involved with SAP. If I configure RCA for BPM will the system be able to analyze the root cause of the iss

  • Charger question

    Can I use the IPad charger to charge the IPhone 4 ? I can put a longer chord on the IPad charger so it is easier to use.

  • Slow death of free disk space

    I have baseline KDE loaded on my Arch installation, on my 16GB flash drive. After last night's -Syu update (I do this at least once every two or three days), the "disk storage space" applet says that whenever I'm running Arch, my free space goes down

  • Error message sldcheck

    Hello togehter, I hope someone coul'd help me. When I check the SLD it comes the following error message: Properties of RFC destination SAPSLDAPI   RFC host: %%RFCSERVER%%   program id:      SAPSLDAPI_UNICODE   gateway host: 192.168.42.43   gateway s

  • Eclipse tptp and weblogic jmx

    Hi all, I am new to eclipse tptp and would want to integrate it into a J2EE application running on Weblogic. So how is tptp different from weblogic JMX feature? In other words, if using all features of tptp, is there still a need to use weblogic's JM