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);

Similar Messages

  • Parameter  to shell script using Runtime.exec(string)

    Hi all, ( Speciall hi to dheeraj tak )
    Briefly : How do i pass an arguement to a non - java executible being called using Runtime.exec.
    In detail : i am using Runtime.exec to call a shell script : The code is as follows:
    String callAndArgs[] = {"/home/tom/jakarta-tomcat-4.1.24/webapps/dash/script.sh"};
    try {
    Runtime rt = Runtime.getRuntime();
    Process child = rt.exec(callAndArgs);
    This works properly & calls the shell script which in turn invokes some other executible (c file).
    $HOME/midi/test/build/bin/<C-EXECUTIBLE>
    Here i am specifying the name (say hello.exe ) . So far so good.
    I want to make this happen dynamiclaly. so i need to pass the name of the executible as a parameter to the script.
    To pass a parameter i hav to change the string to :-
    String callAndArgs[] = {"/home/tom/jakarta-tomcat-4.1.24/webapps/dash/script.sh <C-EXECUTIBLE HERE>"};
    and the script to
    $HOME/midi/test/build/bin/$1 --- where $1 refers to argument 1. (C-EXECUTIBLE AGAIN).
    This is giving an IO - Execption. Plz help
    Code will be very helpful.
    Thanx in advance

    some 1 plz tell me the difference :-
    This is the documentation of Runtime.exec that i found :-
    1> exec
    public Process exec(String command) throws IOException
    Executes the specified string command in a separate process.
    The command argument is parsed into tokens and then executed as a command in a separate process. This method has exactly the same effect as exec(command, null).
    Parameters:
    command - a specified system command
    Complete refernce says : Process (String progName) ----- Executes a program specified by programname as a seperate process.
    2> exec
    public Process exec(String cmdarray[]) throws IOException
    Executes the specified command and arguments in a separate process.
    The command specified by the tokens in cmdarray is executed as a command in a separate process. This has exactly the same effect as exec(cmdarray, null).
    Parameters:
    cmdarray - array containing the command to call and its arguments.
    Complete reference says : Process exec(String comLineArray[]) ---- Executes the command line specified bythe string in comLineArray as a seperate process.
    This means that there is provision 4 command line arguments...
    how do u use it then????????????????????????????

  • 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

  • Getting the output from a Perl script using Runtime.exec

    I cannot get the output from a perl script using Java. Can someone PLEASE help?
    I used the following code:
    Process p = Runtime.getRuntime().exec("C:\\Perl\\bin\\Perl.exe script.pl) ;
    InputSream in = p.getInputStream();
    b...
    do
    System.out.println(b);
    while ((b = in.read()) > 0)
    But there is no way that I get the output in the inputstream. If I use the command "cmd script.pl", the output is displayed in the Dos box, but also not in the inputstream.
    I will appreciate any help.

    Try this
    Process p = Runtime.getRuntime().exec("C:\\Perl\\bin\\Perl.exe script.pl) ;
    BufferedReader rd = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String str;
    while((str=rd.readLine())!=null){
    System.out.println(str);
    Manu

  • Run external programs using runtime class

    Okay, I'm experiencing a really annoying problem with java.lang.runtime
    I'm building a GUI that needs to run some external programs, via a button say. These generally produce a text file or something, so I don't need to stream the output or anything (at least I'm assuming I don't?). Should be very simple...
    So at the terminal (bash) I would type ./programName , and everything will run hunkey dorey.
    In my code then, natrurally, I write
    String cmd = "./programName";
    Process p = runtime.getRuntime().exec(cmd);
    But low and behold...nothing happens. What is going on here, and how do I get around it! ??
    (On windows incidentally, it's no problem at all and works absolutely fine. But when I go over to mac, which is what I need to use, I'm screwed - only adding to the annoyance!)
    Any help would be much appreciated as I have a deadline looming!!

    You need to read the 4 sections of [http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html] and implement the recommendations. Failure to implement all the recommendations will cause you grief.
    P.S. The fragment of code you have posted shows that you have fallen for at least 4 of the traps.

  • 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 wiht Running Batch File using Runtime.exec()

    I am writting one program which will create a jar file using a windows Batch file.
    The main program is in the folder "d:\CmdExec.java".
    The other one to which a jar file to be created is in the folder "e:\folder\HelloWorld.class"
    The contents inside the "e:\folder" are
    e:\folder\HelloWorld.class
    e:\folder\mainClass.txt
    e:\folder\run.bat
    The mainClass.txt contains "Main-Class: HelloWorld"
    The Run.bat file contains "jar cmf mainClass.txt HelloWorld.jar *.class"
    The coding for CmdExec.java is as follows
    import java.io.*;
    import java.awt.Desktop;
    public class CmdExec {
    public static void main(String argv[]) {
    try {
    Desktop desktop = null;
    if (Desktop.isDesktopSupported()) {
    desktop = Desktop.getDesktop();
    desktop.open(new File("e:\\folder\\run.bat"));
    catch (Exception err) {
    err.printStackTrace();
    When i double click the file e:\folder\Run.bat, it will create a jar file for HelloWorld.class.
    But, i want to create that jar file using the java program CmdExec.java.
    When i run CmdExec.java, the batch file is opened. But it shows error as "Can't find the specified file"
    But when i copy the following files to "d:\",
    e:\folder\HelloWorld.class
    e:\folder\mainClass.txt
    the jar file is created using the CmdExec.java.
    But,
    e:\folder\HelloWorld.class
    e:\folder\mainClass.txt
    these files should be in the folder"e:\folder" only.
    Can anyone Help me this Problem?
    Or Anyother way for creating a jar file for one program by using another program?
    Help me soon.............

    Try this. It's not running a bat file. You can say it almost is a bat file.
    import java.io.*;
    import java.util.Scanner;
    public class CmdExec {
        public static void main(String argv[]) {
            try {
                Process p = Runtime.getRuntime().exec("jar cmf mainClass.txt HelloWorld.jar *.class");
                Scanner s1=new Scanner(new InputStreamReader(p.getInputStream()));
                while(s1.hasNextLine())
                    System.out.println(s1.nextLine());
                p.waitFor();
                System.out.println(p.exitValue());
                if(p.exitValue()==0)
                    System.out.println("Okay");
                else
                    System.out.println("Error");
            catch (Exception ex) {
                ex.printStackTrace();
    }Run it in the same folder as mainClass.txt
    Edited by: ColacX on Aug 1, 2008 10:35 AM

  • Why MicroSoft 2000 SR needed while running the script using test manager???

    hi all,
    whenever I trying to run a script using test manager,one POP-UP comes which starts installing MICROSOFT 2000 SR.
    and in few seconds it complaining for some missing component,
    can any body tell me why it is happening.
    what is the need of Microsoft 2000 SR while running the script in test manager.
    tnx
    USOni

    USoni
    I have seen that problem happening before, even that i was never able to figure out why, something that you can try is changing the service log in credentials for both:
    Oracle Application Testing Suite Agent Service
    Oracle Application Testing Suite Application Service
    and use a proper user with admin rights.
    let me know if that helped
    Regards
    Alex

  • How to run shell script using External Process in Process Flow?

    Hi,
    We can run external process using Process flow.
    I would like to run shell script as external process in Process flow.
    Could any one please explain it?
    Thanks and regards
    Gowtham Sen.

    HI,
    As you said I tried this case. I got the following error. The script is running successfully while I tested at unix command prompt.
    The error is as follows..
    tarting Execution PFPS_SMPL_RUNSHELL
    Starting Task PFPS_SMPL_RUNSHELL
    Starting Task PFPS_SMPL_RUNSHELL:EXTERNALPROCESS
    /SOURCE_FILES/CollectFiles.sh: line 1: ls: command not found
    /SOURCE_FILES/CollectFiles.sh: line 1: wc: command not found
    /SOURCE_FILES/CollectFiles.sh: line 1: ls: command not found
    Completing Task PFPS_SMPL_RUNSHELL:EXTERNALPROCESS
    Starting Task PFPS_SMPL_RUNSHELL:EXTERNALPROCESS_1
    SQL*Plus: Release 10.1.0.2.0 - Production on Fri Sep 29 22:57:39 2006
    Copyright (c) 1982, 2004, Oracle. All rights reserved.
    ERROR:
    ORA-12545: Connect failed because target host or object does not exist
    Enter user-name: SP2-0306: Invalid option.
    Usage: CONN[ECT] [logon] [AS {SYSDBA|SYSOPER}]
    where <logon> ::= <username>[<password>][@<connect_identifier>] | /
    Enter user-name: SP2-0306: Invalid option.
    Usage: CONN[ECT] [logon] [AS {SYSDBA|SYSOPER}]
    where <logon> ::= <username>[<password>][@<connect_identifier>] | /
    SP2-0157: unable to CONNECT to ORACLE after 3 attempts, exiting SQL*Plus
    Completing Task PFPS_SMPL_RUNSHELL:EXTERNALPROCESS_1
    Completing Task PFPS_SMPL_RUNSHELL
    Completing Execution PFPS_SMPL_RUNSHELL
    My scenario is---
    I am trying to return a file name from one shell script. I created a external process for that. After completion of this process, I am running another script which takes that file name and trying to create a external table. The both scripts are runnning successfully. But while I am trying to run using process flow, its not coming.
    And I am not getting the way to catch the output of external process and pass it as parameter as another external process.
    Any suggestions are welcome.
    Thanks and regards
    Gowtham Sen.

  • How to run db2 command by using Runtime exec

    Hello
    I am using java. When i am runing db2 command by using Runtime.exec( String cmd, String[] env ). I gave the environment path
    DB2CLP=6259901
    DB2DRIVER=D:\ibm\db2\java\db2java.zip
    DB2HOME=D:\ibm\db2
    DB2INSTANCE=DB2
    DB2MMTOP=D:\CMBISS
    but still I am getting error message
    "DB21061E Command line environment not initialized"
    after setting the above path in the cmd It is working fine. When i am trying thro java programm i am getting the above error. Can I get answer for this.
    bhaski.

    Before you can execute DB2 commands you have to open a DB2 CLP. The following code will do so:
    import java.io.IOException;
    public class Db2 {
         public static void main(String args[]) {
              try {
                   Runtime rt = Runtime.getRuntime();
                   Process child = rt.exec("db2cmd");
                   child.waitFor();
              catch (IOException io) {
                   io.printStackTrace();
              catch (InterruptedException e) {
                   e.printStackTrace();

  • Can we run a java application using Runtime.exec()?

    Can we run a java application using Runtime.exec()?
    If yes what should i use "java" or "javaw", and which way?
    r.exec("java","xyz.class");

    The best way to run the java application would be to dynamiically load it within the same JVM. Look thru the class "ClassLoader" and the "Class", "Method" etc...clases.
    The problem with exec is that it starts another JVM and moreover you dont have the interface where you can throw the Output directly.(indirectly it can be done by openong InputStreams bala blah............). I found this convenient. I am attaching part of my code for easy refernce.
    HIH
    ClassLoader cl = null;
    Class c = null;
    Class cArr[] ;
    Method md = null;
    Object mArr[];
    cl = ClassLoader.getSystemClassLoader();
    try{
         c = cl.loadClass(progName.substring(0,progName.indexOf(".class")) );
    } catch(ClassNotFoundException e) {
    System.out.println(e);
         cArr = new Class[1] ;
         try{
         cArr[0] = Class.forName("java.lang.Object");
         } catch(ClassNotFoundException e) {
         System.out.println(e);
         mArr = new Object[1];
         try{
         md = c.getMethod("processPkt", cArr);
         } catch(NoSuchMethodException e) {
         System.out.println(e);
         } catch(SecurityException e) {
         System.out.println(e);
    try {            
    processedPkt = md.invoke( null, mArr) ;
    } catch(IllegalAccessException e) {
              System.out.println(e);
    } catch(IllegalArgumentException e) {
              System.out.println(e);
    }catch(InvocationTargetException e) {
              System.out.println(e);
    }catch(NullPointerException e) {
              System.out.println(e);
    }catch(ExceptionInInitializerError e) {
              System.out.println(e);
    }

  • Using Run External Script in ICM

    Hi all,
    I am using IPCC enterprise 7.0, during my development on ICM scripting. I am using "Run External Script" to execute IVR script. So my problem is that, any change / update used in IVR subflow will not be effective in ICM until I restart the CRS engine. Which means, the ICM is still running on old IVR script.
    Could anybody advise it? Is it possible to flush the IVR caching?
    Thank you for your attention.

    This URL should help you:
    http://www.cisco.com/en/US/products/sw/custcosw/ps1844/products_tech_note09186a0080236a4d.shtml

  • Running ssh in xterm using Runtime.exec !! URGENT

    I am not able to run the following command using Runtime.exec() but if the same command is executed in shell it gets executed.
    I am working on solais 8
    String toExecStr =
    "xterm -e /bin/sh -c \"ssh [email protected] || echo SSH failed. Press any key to quit.; read a \"";
    System.out.println("Running command :" + toExecStr);
    try {
    Process p = Runtime.getRuntime().exec(toExecStr);
    catch(Exception e){
    e.printStackTrace();
    Any clues .. am i missing something Is there some problem with solaris command ..

    Can some body help me solve this ???

  • Problem of executing a process under Linux using Runtime.exec

    Hi, All
    I am having a problem of executing a process under Linux and looking for help.
    I have a simple C program, which just opens a listening port, accept connection request and receive data. What I did is:
    1. I create a script to start this C program
    2. I write a simple java application using Runtime.exec to execute this script
    I can see this C program is started, and it is doing what it supposed to do, opening a listening port, accepting connection request from client and receiving data from client. But if I stop the Java application, then this C program will die when any incoming data or connection request happens. There is nothing wrong with the C program and the script, because if I manually execute this script, everying works fine.
    I am using jre1.4.2_07 and running under Linux fedora 3.0.
    Then I tried similar thing under Windows XP with service pack2, evrything works OK, the C program doesn't die at all.

    Mind reading is not an exact science but I bet that you are not processing either the process stdout or the stderr stream properly. Have you read http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html ?

  • UNIX script with Runtime.exec and ssh

    I am trying to run a script that is on a UNIX server which doesn't require a password to connect to. Here's my code:
    String _cmd = new String("ssh -l root mach01 \"(/projects/examples/findsw java)\"");
    Process proc = Runtime.getRuntime().exec(_cmd);
    InputStreamReader is = new InputStreamReader(proc.getErrorStream());
    BufferedReader br = new BufferedReader(is);     
    String line = null;
    while ( (line = br.readLine()) != null)
    _logger.error(line);
    proc.waitFor();
    The error outputs:
    ERROR [Thread-7] beans.RunScript - sh: (/projects/examples/findsw java): not found
    INFO [Thread-7] beans.RunScript - _proc.exitValue() = 1
    When I execute _cmd directly from xterm, I have no problems.
    Thanks

    Runtime.exec is not a shell and doesn't run a shell. Try
    adding something like "/bin/sh -c" or whatever shell you use to the beginning of the command.
    BYe!
    EXP

Maybe you are looking for