Runtime exec to run linux scripts

Hi,
I have been having trouble running a simple linux script from within my java program. So far, this is the command line i am passing to the exec() method:
String[] commandArray = {"/bin/sh", "-c", "sh",
"/home/charles/java/ideaProjects/Condor/linuxScripts/LinuxSubmit.sh",
"TwoMinTest.cmd"};
Process proc = rt.exec(commandArray);
The last paramater, "TwoMinTest.cmd" is a varibale that is passed to the script. The command works fine from a linux terminal window but from the java program the process just hangs with no out put from the script (the script does an echo "hello" first). Both the error and input streams obtained from the process do not output anything. If i instert a deliberate mistake into the command the error stream outputs it fine. Any idea why it hangs?
thanks, Charles

I've fixed it for anyone who's interested, this is what i did:
String[] commandArray = {"/bin/sh", "-c", "sh"};
Process proc = rt.exec(commandArray);
OutputStream out = proc.getOutputStream();
PrintWriter p = new PrintWriter(out);
p.println("sh /home/charles/java/ideaProjects/Condor/linuxScripts/LinuxSubmit.sh " +
"TwoMinTest.cmd");
p.flush();
and it flew like a bird.
charles

Similar Messages

  • 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

  • Runtime.exec() on RedHat Linux

    Guys
    Like many before me, it seems, I've having a nightmare with Runtime.exec() across platforms when executing local files.
    I've gone for the basic but robust strategy of writing the required function to a local file and then executing the file. This has worked fine on Windows NT/2000 and on Solaris. But RedHat Linux doesn't want to know.
    I know my permissions are good to execute. I can create the file then run it at the command line, but then whenever I go to run from within Java I get an exit value of 255.
    An old chestnut, I know. But can anyone offer an help?
    Cheers
    Dom

    Here's a small class & main method that illustrates the problem.
    The output I get is:
    File path: /tmp/Temp26345.sh
    chmod +x exit value: 0
    Executing file: 255
    I can then go into /tmp and run ./Temp26345.sh at the command line and get the "ls" command to run.
    import java.io.*;
    public class FileExecutor
         public static void main( String[] args )
              if( args.length == 0 )
                   System.out.println("Arguments must be given: [filename] [writeable]");
                   return;
              try
                   FileExecutor fe = new FileExecutor();
                   File executable = fe.createFile( args[0] , args[1] );
                   fe.executeFile( executable );
              catch( Throwable t )
                   t.printStackTrace();
         public File createFile( String fileName , String contents )
              throws IOException
              //Create the file.
              File tempFile = File.createTempFile( fileName , ".sh" );
              //Write to the file.
              FileOutputStream fos = new FileOutputStream( tempFile );
              OutputStreamWriter osw = new OutputStreamWriter( fos, "UTF-8" );
              int length = contents.length();
              osw.write( contents , 0 , length );
              osw.flush();
              osw.close();
              fos.close();
              return tempFile;
         public void executeFile( File file )
              throws InterruptedException , IOException
              String filePath = file.getAbsolutePath();
              System.out.println( "File path: " + filePath );
              Runtime runtime = Runtime.getRuntime();
              //Actual system permission.     
              Process process_perm = runtime.exec( "chmod +x " + filePath );
              int exitValue = process_perm.waitFor();
              System.out.println( "chmod +x exit value: " + exitValue );
              //Execute the file.
              Process process_exec = runtime.exec( filePath );
              exitValue = process_exec.waitFor();
              System.out.println( "Executing file: " + exitValue );

  • 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 :-)).

  • Strange behavior when using Runtime.exec() to run batch file

    I've been struggling with this for hours.
    I have a Swing application which upon clicking a button, I want to execute a batch file. This batch file itself uses a command window.
    When I use
    Runtime load = Runtime.getRuntime();
    load.exec("cmd /c start c:\\renew\\renew2\\bin\\win\\renew.bat");
    The program (Renew) will start up no problem, but when I exit Renew, the command window stays put. I want the command window to close. Running Renew stand-alone, upon closing Renew, it will exit the command window.
    When I use
    Runtime load = Runtime.getRuntime();
    load.exec("cmd /c c:\\renew\\renew2\\bin\\win\\renew.bat");
    or
    Runtime load = Runtime.getRuntime();
    load.exec("c:\\renew\\renew2\\bin\\win\\renew.bat");
    When I press the button, sometimes the Renew application will come up right away, sometimes the Renew application will come up after a very long delay, and most times, the Renew application will only come up after I have closed the Swing frame where the button is located. When I use this code, the command window that Renew uses is never visible.
    What I want is to simply have the Renew application behave the same exact way launching from my Swing application as when Renew is being run standalone.
    Any suggestions? Thanks so much.
    Sincerely,
    Will

    Getting rid of start makes the startup time very variable. Sometimes it starts up right away, sometimes after many minutes, most times only after I close my application.
    Thanks, Any other suggestions?
    (BTW, I have read the famous "When Runtime.exec() won't" article, and have tried its suggestions to no avail)
    Message was edited by:
    willies777

  • Problem of using Runtime.exec() to run .bat

    hi,
    i try to rum a .bat in the following way:
    Runtime runtime = Runtime.getRuntime();
    Process proc=runtime.exec("cmd.exe /c c:/test.bat");
    int exitVal=proc.waitFor();
    System.out.println("exitVal: "+exitVal);
    but it doesn' t work...
    ,and i get a exit value '1'
    what dose it mean?

    hi,
    i try to rum a .bat in the following way:
    Runtime runtime = Runtime.getRuntime();
    Process proc=runtime.exec("cmd.exe /c c:/test.bat");if it is already a .bat file, why do you invoke it with cmd.exe?? try running it directly as
    Process proc=runtime.exec("c:/test.bat");

  • Help please! [using Runtime.exec() to run find command in UNIX]

    Hi guys! im trying to use exec() to run the UNIX find command
    that my application uses. As you can see from my sample code, the find command finds all files ending with html in my home directory. Unfortunately when I run the program it doesn't give me an output, but when I run it on the shell in the same directory as this code is saved, it works perfectly fine.
    Could someone please help me on this one. Many thanks! =)
    import java.io.*;
    import java.lang.String;
    public class RunCommand {
            public static void main(String[] args) {
                    try {
                            String[] command = {"find", "~/", "-name",
                                            "*.html", "-print"};
                            String find_str;
                            Process find_proc = Runtime.getRuntime().exec(
                                            command);
                            DataInputStream find_in = new DataInputStream(
                                            find_proc.getInputStream());
                            try {
                                    while ((find_str = find_in.readLine())
                                                                    != null) {
                                            System.out.println(find_str);
                            } catch (IOException e) {
                                    System.exit(0);
                    } catch (IOException e1) {
                            System.err.println(e1);
                            System.exit(1);
                    System.exit(0);
    }

    I don't see anythi obvious. In both catch blocks, call printSckTrace on the exception yhou caught.
    I think the real culprit is the ~ though.
    ~ is interpreted by some (most?) shells to men home dir. However, when you just exec a command, you don't have a shell to do that interpretation for you, so it's looking for a directory that's literally named ~.
    Either exec a shell (read the man pages for the shell of your choice, but for zsh I think it's "/bin/zsh -c find ~ blah blah blah) or else just put the actual path to your home directory into the string you pass to exec. You can get that from System.getProperty("user.home").

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

  • How to run linux scripts remotely

    hi,
    My java program has to log in to linux os remotely with userid/pwd and it has to run some shell scripts there. How can i do this?

    Check out the following:
    http://jakarta.apache.org/commons/net/

  • 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 ?

  • Runtime.exec with a unix shell script

    I've done a lot of google'ing and haven't found a definitive answer to my question, including the JavaWorld article that is pointed to quite often. Scenario1 - The program calling Runtime.exec is running in /dir1 and I have a script called test.sh in /dir2 (neither directory are in the path). If I call Runtime.exec("test.sh", null, "/dir2"), I get java.io.IOException: test.sh: not found. However, if I do "touch test.sh" AND "chmod +x test.sh" in /dir1 and call the same exec, it works AND runs the script in /dir2 not /dir1?!?! Also, if I copy /dir2/test.sh /dir1/test.sh and I call exec("test.sh"), it works fine. Scenario2 - If I get rid of /dir1/test.sh and call exec("/dir2/test.sh", null, "/dir2") OR exec("/bin/sh test.sh", null, "/dir2") - both of those work. I just don't get Scenario1. Why does having the dummy executable test.sh in /dir1 allow it to run in /dir2 OR if the script is in the local directory of the process calling exec, why does it work without adding the path? It doesn't seem consistent. Seems like the working directory I specify isn't set before trying to run it or something. On the flip side, if I have a java class in /dir2 called test.class, I can call exec("java test", null, "/dir2") and it just runs without jumping through any hoops - although I think the explanation for that is that "java" is in the path. Let me know what you think.
    Gary

    I think the problem is that the three argument version of exec specifies the command to run (should be full path to it if it is not in the current dir), the environment, then the working directory. The working directory will not help java to find the command to run in the first place. The following does work as you say:
    Runtime.exec("/bin/sh test.sh",null,"/dir2");This is because the full path to the command (/bin/sh) is specified, that runs in directory /dir2 then tries to find test.sh which it finds there.
    Basically to run anything, you should specify the full path in the command, the working directory will not help java find it.
    Dave

  • Runtime.exec(), so much fun

    I'm at the bang your head on the monitor stage of this.
    I have some executables written in C that I need to be able to executed. They require an input file for processing and generate an output file with results, no big deal.
    They both run great from a command prompt. (I'm running on linux with j2sdk1.3.0 by the way)
    Now if I call one of them with Runtime.exec(), it runs perfectly as expected. Everything goes in, Everything comes out, Everyone is happy.
    If I call the other, It says it runs, I get an exit value of 0, the output file is created, but empty.
    I thought I could open a shell with Runtime and then try to get it to run from there to see if it would make any difference, but I was unable to get the shell to call the executables to run with the arguments for input. There is something weird with the way Runtime feeds the strings to the shell. I tried a couple variations.
    Then I thought, what the hell, I wonder if I can write a shell script that calls the executables and see what I get from there. So I wrote a little script that just calls the executable with one little hard coded input, just to see if it would run. Run the script from a command prompt, works great and as expected. Try to call the simple little script from Runtime.exec() and I get a segmentation fault.
    At this point, I'm almost giving up on an easy answer for what in theory should be taking a few lines of code.
    If anybody has a clue on how to approach this or what might be causing this, please let me know.
    for the whole saga
    http://www.javaranch.com/ubb/Forum13/HTML/000198.html
    http://www.javaranch.com/ubb/Forum34/HTML/001360.html
    Any response here would be appreciated.

    I guess clicking on links and reading is too much to
    ask.I admit I didn't read the thread there. Shame on me.
    But i did this litle test.
    Here I have a C program that reads from a file two numbers and writes some lines to another. The names are passed in command line.
    #include <stdio.h>
    #define NAME "[first test program]"
    int main(int argn, char** args) {
      FILE* in = NULL;
      FILE* out = NULL;
      int exitCode = 0;
      int nLoops = 0;
      int nSec = 0;
      int i;
      if(argn < 3) {
        fprintf(stderr, "%s usage: %s inFile outFile\n", NAME, args[0]);
        exitCode = 1;
        goto _exit;
      in=fopen(args[1], "rt");
      if(in == NULL) {
        fprintf(stderr, "%s Cannot open file %s\n", NAME, args[1]);
        exitCode = 2;
        goto _exit;
      out=fopen(args[2], "wt");
      if(out == NULL) {
        exitCode = 2;
        goto _exit;
      fscanf(in, "%d", &nLoops);
      fprintf(stdout, "%s read %d loops from %s\n", NAME, nLoops, args[1]);
      fflush(stdout);
      fscanf(in, "%d", &nSec);
      fprintf(stdout, "%s read %d seconds to sleep from %s\n", NAME, nSec, args[1]);
      fflush(stdout);
      for(i=0; i<nLoops; i++) {
        fprintf(stdout, "%s try to write line %d on %s ... ", NAME, i, args[2]);
        fflush(stdout);
        sleep(nSec);
        fprintf(out, "%s line number %d\n", NAME, i);
        fprintf(stdout, "done\n");
        fflush(stdout);
      fflush(out);
    _exit:
      if(in != NULL) fclose(in);
      if(out != NULL) fclose(out);
      return exitCode;
    }I created an executable c1 and the I modified the NAME and created another executable c2.
    The I wrote a small java test class :
    import java.io.*;
    public class test {
        public static void main(String[] args) {
         String[] cmd1 = { "./c1", "input1", "out1" };
         String[] cmd2 = { "./c2", "input2", "out2" };
         Runtime r = Runtime.getRuntime();
         try {
             Process p1 = r.exec(cmd1);
             Process p2 = r.exec(cmd2);
             BufferedReader r1 =
              new BufferedReader(new InputStreamReader(p1.getInputStream()));
             BufferedReader r2 =
              new BufferedReader(new InputStreamReader(p2.getInputStream()));
             String l1 = r1.readLine();
             String l2 = r2.readLine();
             while(l1!=null || l2!=null) {
              if(l1 != null) System.out.println("from java proc 1:\t" + l1);
              if(l2 != null) System.out.println("from java proc 2:\t" + l2);
              l1 = r1.readLine();
              l2 = r2.readLine();
         } catch (Exception ex) {
             ex.printStackTrace();
    }The imput files contains on a single line the number of lines to write on the output file and a sleep time between lines, like:
    100 1This test runs fine on my linux box.
    I have a RedHat 7.0 on a PIII, kernel 2.2.16-22 .
    You can try and see if it is working on your box. I think it will. My guess is that the problem is somehow on the second c program.
    I didn't read the other thread, so maybe the answer is there, but I'll ask: the problem is with a specific program, or allways happen with the second that you run?
    Anyway, it will be nice if you can isolate the problem in three small source files and send them here.
    Regards,
    Iulian

  • Problems with Runtime.exec inside OC4J in OAS!!! help!!

    Hi all,
    I have a method on my webapplication and the same call a script .cmd on windows and a .sh on unix using Runtime.exec command, inside this script have a call to a java program ie.
    java JMSAdmin < jcajms.txt
    OK, this is fine in OC4J Standalone 10.1.3 in windows and linux but in OAS 10.1.3 the same not run and not throw any error. Its is a BUG ?? limitation ?? OAS ignore a call to another java ??
    please help.
    Tanks

    Normally, you must prepend the command with a call to the command shell (eg /bin/sh).
    But I suspect that this call isn't allowed due to Java EE specification restrictions.

  • Runtime.exec does not work for commands with lengthy outputs

    I need to use Runtime.exec to run some custom commands on a Unix box. I have been doing this for quite some time now and had begun to feel comfortable when recently I started facing a problem. The thing is, whenever there is a command which prints a lot of data on to the console, the program is not able to exit from the waitFor method. Is there some thing that can be done about this?
    Following is a part of the code I use:
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec (command);
    System.out.println ("Got the process");
    int exitValue = p.waitFor();
    System.out.println ("Exit value: " + exitValue);When the output of the "command" is lengthy, it hangs after printing "Got the process".
    PS: By lengthy output, I mean that the command results in printing lines to the console which might be more than 100 in number. Say, something like what "ls -R /" would do in Unix / Linux.

    From java.lang.Process API doc:
    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 Microsoft Windows, or shell scripts. The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (Process.getOutputStream(), Process.getInputStream(), Process.getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. 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.
    So you need to consume the process' output. Check the StreamGobbler example from this article.
    Hope it helps.

  • Runtime.exec() output

    I'm using Runtime.exec() to run a program from within my Java application, but I can't seem to get any of the output from it. I can get the output of some commands, like 'ls' using Process.getInputStream(). Other commands execute , but I don't catch their output. Why can I catch some output, but not other's?
    I'm using Linux, if that makes a difference
    Tyler Ryan

    Also, while playing around with things, I realized the
    process is running native to the directory that my
    program is in (makes sense, but I just hadn't thought
    about it). Is there a way to make the process run
    native to another directory?Do you mean have it start in a different directory than where your process started? Sure, look at the other exec() methods that take different parameters. A couple of them take a File parameter to tell it what directory to start in.

Maybe you are looking for

  • PDF to Word(.doc) document not convert correctly

    Hi I'm trying to convert a pdf file into a word document but i'm unable to do it. the reason is i want to fill in an income tax form which is in a pdf format and i can't add any details in the file... How do i convert this file into a word doc file,

  • Access to message payload at UDF

    Hi, I need to get the message payload at a User Defined Function. I found http://help.sap.com/javadocs/pi/pi711sp03/index.html which have many API class like http://help.sap.com/javadocs/pi/pi711sp03/com/sap/engine/interfaces/messaging/api/Message.ht

  • I`ntel HD Graphics 3000

    Hello, I have a beginning of 2011 mac book with an intel HD Graphics 3000. Since i bought it i had sometimes some black screen for some seconds and some strange restart with also a black screen. Since some days I have this (see the attachment) and i

  • Lables in SAP Script

    Hi,   Is there a way we can find out where the labels are printed from? Regards, BS.

  • About xml discover request

    Hi, I hava some questions as below: 1. I send the XML Discover call to request a list of catalog, it can get info cube and ods cube, ods cube is used to select data? 2. It losts dimension "Request Package" and dimension which own "Navigation Attribut