Runtime.getRuntime().exec() and java.io.FilePermission

Hi all.
I'm trying to run the following code, in an JSP file, inside an Tomcat installation, with Security Manager activated:
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("arp -n -a");But, when I run the JSP, I receive the following error:
java.security.AccessControlException: access denied (java.io.FilePermission <> execute)I have the following config. file:
grant {
  permission java.io.FilePermission "/etc/intranet/intranet.properties", "read";
  permission java.io.FilePermission "/home/projetos/Shofar/conf/ShofarParameters.xml", "read";
  permission java.io.FilePermission "arp", "execute";
  permission java.net.SocketPermission "*:5432",   "accept,connect";
  permission java.lang.RuntimePermission  "selectorProvider";
  permission java.util.PropertyPermission "dns.server",        "read";
  permission java.util.PropertyPermission "dns.search",        "read";
  permission java.net.SocketPermission    "*",                 "resolve";
  permission java.net.SocketPermission    "*:53",              "accept,connect,resolve";
  permission java.io.FilePermission       "/etc/resolv.conf",  "read";
  permission java.net.SocketPermission        "127.0.0.1:465",                                                     "resolve,connect";
  permission java.util.PropertyPermission     "user.name",                                                         "read";
  permission java.io.FilePermission           "/usr/lib/jvm/java-1.5.0-sun-1.5.0.06/jre/lib/javamail.providers",   "read";
  permission java.io.FilePermission           "/usr/lib/jvm/java-1.5.0-sun-1.5.0.06/jre/lib/javamail.address.map", "read";
  permission java.security.SecurityPermission "insertProvider.SunJSSE";
  permission java.util.logging.LoggingPermission "control";
  permission java.util.PropertyPermission "java.awt.headless", "read";
  permission java.io.FilePermission "/tmp/-",                  "read,write,delete";
  permission java.io.FilePermission "/var/lib/tomcat5/temp",   "read";
  permission java.io.FilePermission "/var/lib/tomcat5/temp/-", "read,write,delete";
  permission java.io.FilePermission "/var/lib/tomcat5/work/-", "read,write,delete";
  permission java.util.PropertyPermission "java.io.tmpdir",    "read,write";
  permission java.lang.RuntimePermission "accessClassInPackage.sun.util.calendar";
  permission java.lang.RuntimePermission "accessDeclaredMembers";
  permission java.lang.RuntimePermission "suppressAccessChecks";
  permission java.lang.RuntimePermission "accessClassInPackage.org.apache.jasper";
  permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
};As seen, I put the permission java.io.FilePermission "/usr/sbin/arp", "execute"; line, but it don't work.
What I need to put in the file?

paulcw is right on the money on that one. You can easily create a bat file to perform that operation for you. However if you are feeling a little adventurous you can always use a Process:
Process process=Runtime.getRuntime().exec(.....);
int oneChar;
InputStream inputStream=process.getInputStream();
File file=new File("test.txt");
try{
file.createNewFile();
} catch (Exception e){}
FileOutputStream outputStream=new FileOutputStream(file);
while ((oneChar=inputStream.read())!=-1){
outputStream.write(oneChar);

Similar Messages

  • Runtime.getRuntime().exec and quoted strings?

    Attempting to execute a command containing a quoted string. Being very new to Java I'm guessing I'm not doing it right. Below are two code bits the first one works the second doesn't. So the question is "How do I use quoted strings in a command with .exec?"
    // this one works
    try {               
    p = Runtime.getRuntime().exec("ls -l tst.java");
    p.waitFor();
    System.out.println("Done!");
    catch(Throwable e) {                                  
    system.out.println("Errors!");
    // this one fails
    try {               
    p = Runtime.getRuntime().exec("ls -l \"tst.java\"");
    p.waitFor();
    System.out.println("Done!");
    catch(Throwable e) {                                  
    system.out.println("Errors!");

    I don't know if it is too late for the answer, but I think I know what the problem is.
    You are using exec(String) method, and passed String parameter is parsed using StringTokenizer class. This means that when you use quotes as in "file1 file2", StringTokenizer parses this as "file1 and then file2" so it is not understandable command.
    To solve the problem, do not use exec(String) method, use exec(String[])
    Using this you can send separate command and separate parameters as in following example:
    If you want to send (in Unix)
    grep "SHOW lotid" text.txt
    (using exec("grep \"SHOW lotid\" text.txt") would not work)
    Do the following
    exec(new String[]{"grep", "SHOW lotid", "text.txt"});
    This avoids parsing problem when quotes are used.
    Mehmed

  • Runtime.getruntime().exec and text

    I have an application called Truck Scale. This application has a requirement to talk with devices such as a scale indicator, zebra printer, message boards, rf readers and okidata 395 printers. In this application, we have these devices hooked to a serial mux such as a digi and we are using the JAVA COMM API. However, we are having issues with java comm api where all the data that should be transmitted to the port is not being transmitted. We can however transmitt correctly to the port using the unix shell. I would like to forgo using the Java Comm API and execute everything that needs to send or read info for a port via the unix shell. I know I can do this using the runtime.getruntime().exec. However, my issue arises with oki395. The output that needs to be send via the port (not using lp due to overhead of the unix spooler), is formatted text. When I pass the unix command, the formatted text, and my port to the runtime enviornment via the String array, my formatted text loose all of its formatting including newlines. How can I address this issue with the runtime.getruntime().exec.

    Yes, I can send a new line the port correctly from a command line.
    Here is an example of the text file.
    CROSS PLAINS TN 37049 2549
    MATERIAL SPREAD NOT GUARNTEED.NO PERSONAL CHECKS..
    615-654-9942 TOLL FREE 877-654-9942
    Date: 07/21/2009 02:47:31
    Job No: TC1
    Q Num::
    Cust No: 37206728 Src Num::
    Sold To: CROSS PLAINS UNITED METHODIST CHURCH
    Address: 7665 HIGHWAY 25 E
    CROSS PLAINS,TN 37049
    Ord By:
    Ord No: Rate Zone:
    Location: testing changes
    This text is build using a class we created called textTicket which has each line define as a string with the appropriate newlines and tabs on eac line. As soon as this object is added to the string array and is passed to exec to execute the unix command to pipe it out to the port, the textTicket loses its formatting.

  • Runtime.getRuntime().exec() and waitFor on Windows

    Hi,
    I'm trying to execute a command on Windows 2000 using Runtime.getRuntime().exec(). After that I make a call to waitFor method of the returned process instance. The wait for call blocks and never releases. I'm trying to do simple things, like a call to "cmd /c dir", using commands that I know that work and do release after that. I need to wait for the command terminating to get the output just after that.
    Thanks in advance,
    Marcio Azevedo.

    It's too bad ignoring the streams couldn't be build into ProcessBuilder. Instead you could do it yourself and extend ProcessBuilder like:
    public class MyProcessBuilder extends ProcessBuilder {
      private boolean ignoreInputStream;
      public  MyProcessBuilder(List<String> command) {
         super(command);
      public  MyProcessBuilder(String... command) {
         super(command);
      public boolean ignoreInputStream() {
        return ignoreInputStream;
      public  ProcessBuilder ignoreInputStream(boolean ignoreInputStream) {
        this.ignoreInputStream= ignoreInputStream;
        return this;
      public Process start() {
        Process process = super.start();
        if (ignoreInputStream()) {
             new InputStreamIgnorer(process.getInputStream());
        return process;
      static class InputStreamIgnorer implements Runnable {
        java.io.InputStream in;
        InputStreamIgnorer(java.io.InputStream in) {
          this.in = in;
          new Thread(this,"InputStreamIgnorer Thread").start();
        public void run() {
          int ch;
          try {
            while((ch = in.read()) != -1) {
                //System.out.print(ch);
          } catch (java.io.IOException ex) {} //ignore
    }Then it could be simpled used like:
    new MyProcessBuilder("cmd","/c", "dir").redirectErrorStream(true).ignoreInputStream(true).start().waitFor();

  • Runtime.getRuntime().exec() and Garbage Collection

    I am programming a piece of software in both Java and C that has some strict real time requirements. Garbage collection, which pauses all threads in Java, sometimes causes loss of incoming data. In order to get around this, I am thinking to start another process using Runtime.getRuntime().exec("c_program") and using interprocess controls (in a UNIX environment) to retrieve data from the new process.
    My only worry is that the Process created by the above call would be a child process of whatever JVM thread created it, (as far as I understand, the JVM implementation in Unix uses multiple processes) and would also be paused when garbage collection occurs. Does anyone know the implementation of the exec functionality and the JVM well enough to say that this will or will not happen?
    Thanks in advance,
    Benjamin

    You're going to create a whole new process? I don't
    know what a "child process" means, but Runtime.exec()
    gets the operating system to produce an entirely new
    process, outside the JVM. However if it produces
    output on stdout or stderr, you're going to have
    threads in your JVM that read that output, otherwise
    that process will hang.
    Why is your idea better than just calling the C
    program via JNI?Thank you both for your replies. My plan was to create a whole new process, yes. In UNIX, a process C is created by another process P using fork() or the exec() family. Process P is then the parent of process C, and process C is the child of Process P. P has an amount of control over C since it can send various signals to pause, kill, etc to C.
    My concern was that the JVM implementation would use these signals to implement the pause of all threads before garbage collecting. If it did, it may also pause the Process that it spawned from the Runtime.exec() call. Pausing my C program in this manner would cause the loss of data I was trying to avoid in the first place.
    My plan for the new process was not to produce anything on stdout or stderr, but to pass data back to the JVM using ipc (interprocess communication) resources of UNIX. I would have to use the JNI to access these resources.
    The whole reason for wanting to do this is to avoid the pause during garbage collection that all Java Threads experience. If I were just to call the C program through the JNI with a normal Java Thread as I think you were suggesting, this Java Thread would still be paused during garbage collection.
    To the second reply about RTSJ, I had heard about this but couldn't find info about it! Thanks for the link. I'm checking it out at the moment. The java runtime must be considerably different for the specifications I see that they guarantee.
    Again, thanks for the replies,
    Benjamin

  • Runtime.getRuntime().exec() and rewind of stdin

    Hello-
    I have a need to use exec() to call a process that takes it's inputs on stdin, and outputs to stdout and stderr. On simple test cases, this all works fine with proc.getErrorStream(), proc.getInputStream(), and proc.getOutputStream(), with data being passed with BufferedReaders and BufferedWriters.
    However, my program (written in fortran) takes the stdin it receives and rewinds it (rewind 5) after reading through it once. This causes my program to crap out when I flush my OutputStream. If i don't flush / close the OutputStream, my program deadlocks. Any idea what to check for?
    Here's my class that i call:
    class InWriter extends Thread {
      OutputStream os;
      String in;
      BufferedWriter out;
      public InWriter(OutputStream os, String input){
         this.os = os;
         this.in = input;
      public void close(){
         try{
           out.flush();
           out.close();
         }catch(Exception e){
           System.out.println("Error when trying to close stdin stream:");
           e.printStackTrace();
      public void run(){
            try {
           int write = 1024;
           System.out.println("input length: " + input.length());
           out = new BufferedWriter(new OutputStreamWriter(os), write);
             out = new BufferedOutputStream(os, write);
           int wrote = 0;
           int left = 0;
             while(wrote < input.length()){
              left = input.length() - wrote;
              if(left < write){
              out.write(inputB, wrote, left);
              else{
              out.write(inputB, wrote, write);
              wrote += write;
           close();
           catch(Exception e){
          System.out.println("Error writing to stdin");
          e.printStackTrace();
    }any info greatly appreciated!
    -Ed

    tkleisas: the process is crapping out when I call flush()
    BIJ : I would think a stream is NOT inherently rewindable / un-seekable, since you can mark and reset InputStreams. As a workaround, I am currently writing an intermediate file, and calling the fortran program with file redirection (i.e. "cmd /C myprogram < inputfile"), which works fine, but we would prefer not to have to do it this way.
    I've also tried different ways to write out via a FileChannel, but I can't seem to sync up FileDescriptor.in and the outputstream I get from the process.
    byte[] inputB = input.getBytes();
    ByteBuffer bb = ByteBuffer.allocateDirect(input.length());
    Bb.put(inputB, 0, input.length());
    FileOutputStream fs = new FileOutputStream(FileDescriptor.in);
    FileChannel fc = fs.getChannel();
    int numBuffersNeeded = (input.length() / write) + 1;
    ByteBuffer[] bbs = new ByteBuffer[numBuffersNeeded];
    wrote = 0;
    left = 0;
    byte[] tempb = new byte[write];
    ByteBuffer tempB = ByteBuffer.allocateDirect(write);
    for(int i = 0; i < numBuffersNeeded; i++){
           left = input.length() - wrote;
           //System.out.println("left: " + left);
           //System.out.println("Writing " + i + " of " + numBuffersNeeded);
           if(left < write){
                System.arraycopy(inputB, (i * write), tempb, 0, left);
           else{
                System.arraycopy(inputB, (i * write), tempb, 0, write);
           tempB = ByteBuffer.allocateDirect(write);
           tempB.put(tempb, 0, write);
           bbs[i] = tempB;
           wrote += write;
    //FileDescriptor.in.sync();
    //System.out.println("bb length: " + bb.length);
    //fc.write(bb);
    //bb.rewind();
      fc.write(bbs);
      fc.close();
      fs.close();

  • Runtime.getRuntime().exec() and waitFor()

    I have a problem where waitFor doesn't work as it should due to the fact that cmd.exe really did terminate.
    I'm executing a
    cmd.exe /c c:\abc.xml
    the xml is a word document, the cmd.exe will terminate, and word will open. I need to somehow keep the cmd.exe opened so the waitFor doesn't just finish.
    If I do cmd.exe /c c:\abc.doc, the word will open under cmd.exe, hence cmd.exe doesn't terminate, it's just this xml case.
    Someone enlighten me.
    thx

    Well because I don't know if that xml is just a text xml or a word xml...
    doing cmd /c whatever.xml will let the computer decide what it is and open the appropriate application to read it. But for some reason cmd terminates after opening that determined software, while if I do something like cmd /c whatever.DOC it'll open word under the cmd process and cmd won't terminate.

  • Unable to execute Runtime.getRuntime().exec(

    Hello,
    I am new to Java programming and trying to execute (OS is Linux) an external jar File with the command:
    Runtime.getRuntime().exec("nohup java -jar SeismicAgents.jar &");It should start the SeismicAgents.jar and write the output to nohup.out.
    This works perfectly if I just enter the command at the command line.
    But upon starting it from within my program, the process seems to be started (I can see it when executin "ps aux"), but it is obviously not running as no input is written to nohup.out and the file which SeismicAgents.jar should generate is not generated.
    I also tried the following code:
    String cmd[] = {"nohup", "java", "-jar", "SeismicAgents.jar", "&"};
    Runtime.getRuntime().exec(cmd);But I am experiencing the same problem here.
    Executing something like
    Runtime.getRuntime().exec(ls);works without problems...
    Can anyone help?

    Runtime.getRuntime().exec("nohup java -jar
    SeismicAgents.jar &");Java does not interprete the '&' character. Neither does
    nohup. You would have to prefix this with /bin/sh -c, put
    the rest in quotes and, most importantly, redirect input
    and output somewhere. Without redirection, it is the task
    of your java program to feed the subprocess with input
    and drain its stdout and stderr buffers.
    Executing something like
    Runtime.getRuntime().exec(ls);works without problems...It is hard to believe this. Either it should be "ls" or
    ls is string variable containing the relevant string,
    but even then I would be surprised if you see any
    output on the command line. At least I don't get
    anything with public class bla {
      public static void main(String[] argv) throws Exception {
        Runtime.getRuntime().exec("ls");
    }If you don't want a "/bin/sh -c" hack, you may want to
    try http://www.ebi.ac.uk/~kirsch/monq-doc/monq/stuff/Exec.html .
    Harald.

  • Problems with Runtime.getRuntime().exe and getting output. Please Help me!!

    I'm creating a program that runs the followings programs written in C and compiled with gcc:
    ==========================The first C program====================================
    #include<stdio.h>
    void leia();
    main()
    int x = 20;
    int y = 2;
    printf( "Marcinho e Danny\n" );
    printf( "Te\n" );
    printf( "Vida\n" );
    printf( "Marciorja: %d.\n", x * y );
    ===============================================================================
    ==========================The second C program====================================
    #include<stdio.h>
    void leia();
    main()
    int x = 20;
    int y = 2;
    printf( "Marcinho e Danny\n" );
    printf( "Te\n" );
    printf( "Vida\n" );
    printf( "Marciorja: %d.\n", x * y );
    scanf( "%d", &x ); //This is the statement added to the latter C program.
    ===============================================================================
    I compiled this C program and generates the a.exe program. I have the following Java program:
    ==================================================================================
    import java.awt.Color;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.util.StringTokenizer;
    import javax.swing.JFrame;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.EditorKit;
    import javax.swing.text.MutableAttributeSet;
    import javax.swing.text.Style;
    import javax.swing.text.StyledDocument;
    import javax.swing.text.StyledEditorKit;
    public class Teste
    private BufferedWriter out;
    private BufferedReader in;
    private Style stylePrompt;
    private LeitorDeEntrada le;
    private String entrada = "";
    private AreaDeEdicao areaDeTexto;
    Process p = null;
    public Teste( AreaDeEdicao areaDeTexto )
    this.areaDeTexto = areaDeTexto;
    public void runCommand( String command ) throws IOException
    StringTokenizer strTokenizer = new StringTokenizer( command );
    String mainCommand = null;
    String argument = null;
    StyledDocument doc = areaDeTexto.getStyledDocument( );
    String[] prefix = new String[] { "cmd.exe", "/c", command };
    p = Runtime.getRuntime().exec( prefix, null, new File( System.getProperty( "user.dir" ) ) );
    in = new BufferedReader( new InputStreamReader( p.getInputStream( ) ) );
    out = new BufferedWriter( new OutputStreamWriter( p.getOutputStream( ) ) );
    out.flush();
    Thread t = new Thread( )
    public void run( )
    super.setName( "Marcio" );
    execute( );
    public void execute( )
    String c = null;
    try
    if( !in.ready( ) )
    try
    this.sleep( 1000 );
    catch( InterruptedException e2 )
    e2.printStackTrace( );
    System.out.println( "in.rea: " + in.ready( ) );
    c = in.readLine( );
    catch( IOException e )
    e.printStackTrace( );
    String str = "";
    while( c != null )
    str = c + "\n";
    try
    areaDeTexto.getDocument( ).insertString( areaDeTexto.getDocument( )
    .getLength( ),
    str, null );
    catch( BadLocationException e3 )
    e3.printStackTrace( );
    try
    c = in.readLine( );
    catch( IOException e2 )
    e2.printStackTrace( );
    areaDeTexto.setCaretPosition( areaDeTexto.getDocument( )
    .getLength( ) );
    try
    in.close( );
    catch( IOException e1 )
    e1.printStackTrace( );
    t.setDaemon( true );
    t.start( );
    le = new LeitorDeEntrada( );
    areaDeTexto.addKeyListener( le );
    public static void main( String[] args )
    JFrame janela = new JFrame( );
    AreaDeEdicao areaDeTexto = new AreaDeEdicao( new MyDocument( ) );
    areaDeTexto.setBackground( Color.black );
    areaDeTexto.setForeground( Color.GREEN );
    janela.getContentPane( ).add( areaDeTexto );
    Teste teste = new Teste( areaDeTexto );
    try
    teste.runCommand( "a.exe" );
    catch( IOException e )
    e.printStackTrace( );
    janela.setSize( 500, 300 );
    janela.setVisible( true );
    class LeitorDeEntrada extends KeyAdapter
    public void keyPressed( KeyEvent e )
    char c = e.getKeyChar( );
    System.out.println( "keyPressed" );
    try
    if( c == '\n' )
    areaDeTexto.getDocument().insertString( areaDeTexto.getDocument( )
    .getLength( ),
    c + "", null );
    out.write( c + "" );
    out.flush();
    catch( BadLocationException e2 )
    e2.printStackTrace( );
    } catch (IOException e2) {
    e2.printStackTrace();
    ==================================================================================
    This Java program is very simple. It runs the a.exe using the method Runtime.getRuntime().exec and gets input for a.exe from a JTextPane and shows the output in the same JTextPane.
    If my a.exe represents the binary code of the first C program the text in the JTextPane is the correct output of the a.exe. But, if my a.exe represents the binary code of the second C program, the JTextPane shows the messages ( "Marcinho e Danny\n", "Te\n", "Vida\n", "Marciorja: %d.\n") after I enter the value claimed by the scanf.
    I tested my Java program running programs that require input and all have the same behavior:.
    What can I need to do to solve this bug?
    I read other posts with the same problem and nobody answers what is the problem.
    I'LL pay 10 Duke dollars to the first that answers me.

    The second C program with the statement fflush( stdout ) produces the right output.
    #include<stdio.h>
    void leia();
    main()
    int x = 20;
    int y = 2;
    printf( "Marcinho e Danny\n" );
    printf( "Te\n" );
    printf( "Vida\n" );
    fflush( stdout ); //added statement.
    printf( "Marciorja: %d.\n", x * y );
    scanf( "%d", &x ); //This is the statement added to the latter C program.
    but what can I do to run C programs that doesn't flush the stdout?

  • Running curl command from a java program using Runtime.getRuntime.exec

    for some reason my curl command does not run when I run it from within my java program and errors out with "https protocol not supported". This same curl command however runs fine from any directory on my red hat linux system.
    To debug the problem, I printed my curl command from the java program before calling Runtime.getRuntime.exec command and then used this o/p to run from the command line and it runs fine.
    I am not using libcurl or anything else, I am running a simple curl command as a command line utility from inside a Java program.
    Any ideas on why this might be happening?

    thanks a lot for your response. The reason why I am using curl is because I need to use certificates and keys to gain access to the internal server. So I use curl "<url> --cert <path to the certificate>" --key "<path to the key>". If you don't mid could you please tell me which version of curl you are using.
    I am using 7.15 in my system.
    Below is the code which errors out.
    public int execCurlCmd(String command)
              String s = null;
              try {
                  // run the Unix "ps -ef" command
                     Process p = Runtime.getRuntime().exec(command);
                     BufferedReader stdInput = new BufferedReader(new
                          InputStreamReader(p.getInputStream()));
                     BufferedReader stdError = new BufferedReader(new
                          InputStreamReader(p.getErrorStream()));
                     // read the output from the command
                     System.out.println("Here is the standard output of the command:\n");
                     while ((s = stdInput.readLine()) != null) {
                         System.out.println(s);
                     // read any errors from the attempted command
                     System.out.println("Here is the standard error of the command (if any):\n");
                     while ((s = stdError.readLine()) != null) {
                         System.out.println(s);
                     return(0);
                 catch (IOException e) {
                     System.out.println("exception happened - here's what I know: ");
                     e.printStackTrace();
                     return(-1);
         }

  • Wierdness w/ Runtime().getRuntime().exec between 8.1.6 and 8.1.7

    A Java SP that executes OS commands runs fine in 8.1.6, but doesn't run in
    8.1.7 when a window is generated as a result of the call. The Java class
    follows:
    package com.crtinc.oracle.util.osrun;
    import java.io.*;
    public class SimpleRunner extends Object {
    //just run the daggone command, don't worry about any errors, feedback,
    etc...
    public static void run(String cmd) throws IOException {
    Runtime.getRuntime().exec(cmd);
    The call spec follows:
    CREATE OR REPLACE PACKAGE SIMPLERUNNER AUTHID CURRENT_USER AS
    PROCEDURE RUN ("cmd" IN VARCHAR2)
    AS LANGUAGE JAVA
    NAME 'com.crtinc.oracle.util.osrun.SimpleRunner.run(java.lang.String)';
    END SIMPLERUNNER;
    When deployed to v8.1.6 by a user with JAVASYSPRIV, the following call from
    SQL*Plus runs and displays a window:
    exec simplerunner.run('notepad.exe');
    When deployed to v8.1.7, the same call causes notepad.exe to be added to the NT
    Task Manager Processes tab, but the notepad window doesn't actually open up.
    FWIW, the above code is a simple example - myactual utility captures the
    output streams of OS commands, very much along the lines of sample code that
    I've seen on Metalink - this also works fine in 8.1.6, but never returns in
    8.1.7.
    Granted, running Notepad is of limited utility (though it demos very well :-),
    but other useful OS commands that spawna window (such as kicking of an Oracle
    Report, which pops up a small status window) do not run now in 8.1.7. Running
    a completely non-visual process seemsto work fine, however.
    Any help much appreciated!
    Thanks
    Jim

    Well, just for anyone who might be facing such an issue in the future...
    I am running the databse on NT and it turns out that my NT service didn't have the 'Allow Service to Interact with Desktop' checkbox selected, so that's why OS commands that generated windows weren't showing up. Checking that checkbox and stopping/restarting the service solved the problem.
    Jim
    null

  • Runtime.getRuntime().exec hangs and doesn't print the output

    Hi,
    I have written the following code to execute the command "psexec ipaddress -u userid -p password -l -c execute.exe >> c:/25_showoutpout.txt" and print the output in 25_showoutpout.txt file.
    import java.io.*;
    public class ExecTest{
         public static void main(String args[]) throws IOException{
         String args1 = "psexec ipaddress -u userid -p password -l -c execute.exe >> c:/25_showoutpout.txt";
         try{
         Process p=Runtime.getRuntime().exec(args1);
    int i = p.waitFor();
         System.out.println("Done.with time "+i);
         }catch(Exception e){
              System.out.println("The error is "+e);
    But this program hangs and creates a blank 25_showoutpout.txt file.In the process list I can see the process running, but it doesn't redirect the output in the txt file.When i run the command from the command line it runs fine.Please help me.
    Thanks in advance

    Hi,
    I have written the following program to get the output.But still the required output is not coming in the console file.Only the messages that gets printed in the parent console that is coming in the file.But the expected output is to get the messages from the child window which gets executed while the .exe runs.
    import java.io.*;
    public class RuntimeExecTest{
    public static void main(String args[]){
    String s = null;
    String result= null;
    int count =0;
    try{
              // read the output from the command
    String cmd = "cmd.exe /c D:/installer/PsTools.zip/PsTools/psexec.exe ipaddress -u userid -p password -l -c excute.exe >> C:/RuntimeExec_25.txt";
         Process p = Runtime.getRuntime().exec(cmd);
         InputStream is = p.getInputStream();
         // Get the std in to the process.
         OutputStream os = p.getOutputStream();
         // Get the std err from the process.
         InputStream es = p.getErrorStream();
         // Create readers for those streams.
         BufferedReader reader = new BufferedReader(new InputStreamReader(is));
         BufferedReader errReader = new BufferedReader(new InputStreamReader(es));
         String line;               
         // Read STDOUT into a buffer.
         // If no STDOUT check STDERR.
         while((line = errReader.readLine()) != null){
              // Do something with data here if you wish.
         System.out.println( line );
         while((line = reader.readLine()) != null){
              // Do something with data here if you wish.
         System.out.println( line );
         System.exit(0);
    catch( Exception ex )
    ex.printStackTrace();
    }

  • Runtime.getRuntime().exec(...) problems and exit codes

    Hi,
    I am trying to launch an application 4 times with different arguments from a Java app. I have tried doing it sequentially and in four different threads, but the results are the same: sometimes the 4 of them are properly launched, sometimes (the most of the times) only 3 are launched and sometimes only 2. I have tried with cmd and cmdarray[] as parameters for exec but the results are the same.
    This is one of the four threads I use:
    Runnable r1 = new Runnable(){
                        public void run(){
                             String ecgCommand = "./flute -S -m:" + Config.ECGS_FLUTE_IP + " -p:" + Config.ECGS_FLUTE_PORT + " -F:" + Config.ECGS + " -r:" + Config.ECGS_FLUTE_RATE + " -C";
                             System.out.println(ecgCommand);
                             InputStream ecgsStream = null;
                             InputStreamReader isr = null;
                             BufferedReader br = null;
                             try{
                                  ecgsProcess = Runtime.getRuntime().exec(ecgCommand, null, new File(Config.HOME_PATH + Config.FLUTE_PATH));
                                  String line;
                                  ecgsStream = ecgsProcess.getInputStream();
                                  isr = new InputStreamReader(ecgsStream);
                                  br = new BufferedReader(isr);
                                  StyledDocument styleDoc = mm.ecgFluteMessages.getStyledDocument();
                                  Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
                                  while((line = br.readLine()) != null && running){
                                       if(styleDoc.getLength() > 25000)     mm.ecgFluteMessages.setText("");
                                       styleDoc.insertString(styleDoc.getLength(), line+ "\n", def);
                                       mm.ecgFluteMessages.setCaretPosition(mm.ecgFluteMessages.getDocument().getLength());
                                  System.out.println(ecgsProcess.waitFor());
                             }catch(Exception e){
                                  try {
                                       br.close();
                                       isr.close();
                                       ecgsStream.close();
                                  } catch (Exception e1) {
                                       e.printStackTrace();
                   new Thread(r1).start();Adding a Thread.sleep between runnables doesn't have any effect.
    In addition, those processes that are not properly launched return an exit value of 255. I have searched for its meaning but I have found nothing. Could anybody tell me where can I find a list of the JVM exit codes in order to guess what is happening?
    Can anybody help me with this issue? Help is much appreciated.
    Thanks a lot

    I have been looking for it but it seems it has not any exit code list or any documentation regarding this. Anyway, I think 255 is a JVM error code (the last one, errors are numbered in modulo 256) which means that the error has nothing to do with JVM but with the application execution (flute in my case).
    I have added a prompt for the errorStream and I have this message for the 255 exited programs:
    not well-formed (invalid token) at line 15+
    And the four commands are like this:
    *./flute -S -m:239.255.255.253 -p:60102 -F:./ecgs -r:150 -C*
    *./flute -S -m:239.255.255.252 -p:60103 -F:./ads -r:150 -C*
    *./flute -S -m:239.255.255.251 -p:60104 -F:./pushvod -r:50 -C*
    *./flute -S -m:239.255.255.250 -p:60105 -F:./banners -r:150 -C*
    So, as the process is sometimes initialized properly and others it is not, it seems that there is a problem with the tokenizing of the command not happening always. As I have tried it with a single command line and with an array of command strings (the first for "./flute" and the followings for each argument) with the same results I can't understand why is this problem happening sometimes. Happening always would help me in giving a clue but that's not the case.
    Any idea? Thanks a lot.
    Edited by: dulceangustia on Apr 3, 2008 3:41 AM

  • Runtime.getRuntime().exec(java test)

    Hi,
    As part of a thesis for college, I am trying to execute a test java program. The program executes okay and I can read the results okay.
    Sample code.
    process = Runtime.getRuntime().exec("java test");
    InputStream iOutStream = process.getInputStream();
    InputStream ErrorStream = process.getErrorStream();
    However, I need to be able to execute a progam that reads a parameter from the screen. I tried to pass a parameter file but it doesn't work.
    process = Runtime.getRuntime().exec("java test <input.txt");
    I also tried just passing the parameters as a string array but it doesn't work either.
    process = Runtime.getRuntime().exec("java test 2, 2");
    Is there any other way that I can get the process to accept parameters?
    My deadline is looming so any help would be greatly appreciated.
    Thanks
    Eleanor
    [email protected]

    I think you are waiting when reading the output before you write to the stream until it becomes NULL or -1. That will never finish if the program you execute is expecting input!
    See a working example:
    This class does nothing than print a line on the console, then waits for a line of input, then prints the result again on the console. This is the class you'd execute from some other java code:
    import java.io.*;
    public class Input {
        public static void main(String args[]) {
            try {
                System.out.println("Before input");
                BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
                String s=r.readLine();
                System.out.println("Got line : " + s);
            } catch(Exception e) {
                    System.out.println(e.getMessage());
    }The following 'controls' the input-test class above, so compile the classes and execute the following one:
    import java.io.*;
    import java.lang.*;
    public class test {
        public static void main(String args[]) {
            try {
                Process p = Runtime.getRuntime().exec("java Input");
                BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
                BufferedWriter w = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
                String s=r.readLine(); // You cannot read until NULL because that will not happen before you have 'input' something
                System.out.println("Got: " + s);
                w.write("cvxcvxcvx\n\r");
                w.flush();
                System.out.println("waiting result:");
                while( (s=r.readLine()) != null) { // read until finished.
                    System.out.println("after : " + s);
            } catch(Exception e) {
                    System.out.println(e.getMessage());               
    }

  • Pls help me about Runtime.getRuntime().exec("java...")

    I have two applications. One is Client, the other is Platform.
    In the Platform, there are source files packaged into a library named ZtConfig.jar used by Client. If run Client and Platform, two applications can execute normally.
    But if Client is started by user from platform, there is something wrong.
    I noticed the error difficultly with finally catching exception.
    I was puzzled. It is so strange. Pls help me. I list some codes here.
    In Client where finally exception catched:
    import zt.config;
            try {
              xmlFileUrl = new java.net.URL(
                  "file:///e:/Client/src/config/nsr1000.xml");
            catch (IOException ex1) {
              FileLogger.error(ex1.getMessage());
            FileLogger.info("NSR1000Document.setIEDContent", xmlFileUrl.toString());
            try {
              xmlLoader = new XMLConfigLoader(xmlFileUrl);
            finally {
              FileLogger.error("NSR1000Document.setIEDContent",
                               "cannot new XMLConfigLoader object");
              return; // the following codes cannot execute, so have to return here.
    In the XMLConfigLoader, the constructor is
      public XMLConfigLoader(java.net.URL xmlFileUrl) {
        this.xmlFileUrl = xmlFileUrl;
        configDoc = null;
        builder = null;
        xmlDoc = null;
    Platform start Client application using the following code
      Runtime.getRuntime().exec(
                    "java -jar e:/Client/Client.jar");

    I've got it!
    Briefly, it is because classpath setting was overwritten by JBuilder.
    Firstly, I start Platform from JBuilder. In its messages window. The command is
    d:\j2sdk1.4.2_06\bin\javaw -classpath "JBPATH" zt.client.nsr1000.NSR1000App
    Now, classpath environment variable was changed to be JBPATH. While I start
    Client use Runtime.getRuntime().exec("java -jar Client.jar"), it will not run for classpath changed.
    Then, I configured all packages used by Client into JBuilder libraries, including
    Client.jar. And changed codes Runtime.getRuntime().exec("java -jar Client.jar") to be Runtime.getRuntime().exec("java -Xmx128m zt.client.nsr1000.NSR1000App")
    I also changed CLASSPATH windows system environment variable.
    I found this from command console, it can display exceptions. But from JBuilder, there is no exception that can be captured. So debug is difficult.

Maybe you are looking for

  • I've got the old Ipod touch and i want to update it but i can't!

    I've got the old ipod Touch and everytime i want to download something it will say i need an update!! Ive tried nearly everything don't know how to make it work

  • Profit Center Is not in Controlling Area BP01

    Hi I am getting the below error. Please help me Profit center 2100 is not created in Controlling Area BP01 Message no. FAGL_ORG_UNITS001 Thanks Surya

  • MobileMe albums not visible in Aperture after upgrade from iPhoto

    I've just upgraded from iPhoto to Aperture and all went well, except that my mobileme albums aren't appearing. I published a test album which worked, but my existing ones don't appear. I've read on another thread that a dodgy character in an album na

  • Movement type 542

    hello, friends. the requirement is to reflect the number of the customer/vendor in material document associated with movement type 542.  can this be copied from sales documents like the returns order or inbound delivery? thanks.

  • Optional Deployment with Deadline

    I want a deploy a Office 2013 package and my design is like that ; 1. The package content should be downloaded by all the clients as soon as possible. 2. Users should have option to install this package until the deadline that I set this package for.