Runtime.exec on Linux

Hi,
I'm having some difficulty getting Runtime.exe() to work on Linux. I was trying to run "make oldconfig" from my Java program.
public Action()
   Process p = Runtime.getRuntime().exec ( "make oldconfig" );
   InputStream processStream = p.getInputStream();
   OutputStream commandStream = p.getOutputStream();
   InputStream procErrorStream = [/getErrorStream();
   p.waitFor ();
private void outputData ()
   int hasInput;
   if  ( ( hasInput = processStream.available() ) >0 )
      byte[] buffer = new byte [hasInput];
      int len = processStream.read(buffer);
      if ( len > 0 )
         System.out.println( new String ( buffer, 0, len ) );
   if  ( ( hasInput = procErrorStream.available() ) >0 )
      byte[] buffer = new byte [hasInput];
      int len = procErrorStream.read(buffer);
      if ( len > 0 )
         System.out.println( new String ( buffer, 0, len ) );
}I don't see any errors from this command, but it doesn't look like the "make oldconfig" is called because I'm not seeing any outputs. Can anyone help or give me some hints to debug this? Thanks.

The line
InputStream procErrorStream = [/getErrorStream();
looks a bit dodgy to me

Similar Messages

  • How to make Runtime.exec call Linux exec?

    Howdy,
    I am trying to use a combination of 'find' and 'rm' to delete all files with a certain extension in a directory and all of its subdirs.
    Here's the command:
    Process proc = runtime.exec("find " + dir + " -name '*.vcs' -exec rm -rf {} \\;");
    It's failing, not sure why, the exitCode is 1 instead of 0. I'm not sure if it's because I have to escape the '\' character, or if it's because I am calling Linux's 'exec' function within a Java exec() call, or something else entirely.
    The easiest thing to do would be to just use rm, but that doesn't seem to be an option. With rm it seems to be all or nothing -- If I try:
    rm -rf *.vcs
    it fails if it doesn't find a file with that extension in the start directory (even though I've specified -r). But if I enter:
    rm -rf *
    it nukes my directories AND files, something I don't want to happen. I realize this is a Linux thing, I'm just explaining it here as background, just in case.
    Anyway, so is there a way to do this? Perhaps with another system call, without using Linux's exec()?
    Many thanks
    Bob

    import java.io.*;
    public class ExecutingALinuxCommand
        static class PipeInputStreamToOutputStream implements Runnable
            PipeInputStreamToOutputStream(InputStream is, OutputStream os)
                is_ = is;
                os_ = os;
            public void run()
                try
                    byte[] buffer = new byte[1024];
                    for(int count = 0; (count = is_.read(buffer)) >= 0;)
                        os_.write(buffer, 0, count);
                catch (IOException e)
                    e.printStackTrace();
            private final InputStream is_;
            private final OutputStream os_;
        public static void main(String[] args)
            try
                String dir = System.getProperty("user.home") + "/work/dev";
                String[] command = {"sh","-c", "find " + dir + " -name '*.java' -exec grep -l Runtime {} \\;"};
                final Process process = Runtime.getRuntime().exec(command);
                new Thread(new PipeInputStreamToOutputStream(process.getInputStream(), System.out)).start();
                new Thread(new PipeInputStreamToOutputStream(process.getErrorStream(), System.err)).start();
                int returnCode = process.waitFor();
                System.out.println("Return code = " + returnCode);
            catch (Exception e)
                e.printStackTrace();
    }

  • Runtime.exec() under Linux

    My game's installer works on windows and mac but on linux it's getting this error:
    java.io.IOException: Cannot run program "javaw": java.io.IOException: error=2, No such file or directory
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    Here's my code:
      public void runProgram(){
        String dir = folder;
        if(os_type == LINUX && dir.charAt(0) != '/'){
          dir = "/"+dir;
        File file = new File(dir+"SFC_Updater.jar");
        if(file.isFile() == false){
          System.err.println("Could not find updater jar: "+file.getPath());
          throw new RuntimeException();
        if(os_type == LINUX){
          System.err.println("Attempting to run with special linux arguments because linux is SPECIAL!");
          String[] args = new String[4];
          args[0] = "javaw";
          args[1] = "-jar";
          args[2] = "\""+dir+"SFC_Updater.jar\"";
          args[3] = dir;
          try{
          Runtime.getRuntime().exec(args);
          catch(Exception e){
           System.err.println("Linux Fails.");
           e.printStackTrace();
        else{
          try{
            Runtime.getRuntime().exec("javaw -jar \""+dir+"SFC_Updater.jar\" "+dir);
          catch(Exception e){
            e.printStackTrace();
      }Thanks

    Have you tried including the full path for javaw in
    the Linux version?It is interesting to note that the Linux version does not have a javaw

  • Runtime.exec() on Linux RedHat. help!!

    Guys
    I've having a lot of problems with Runtime.exec() across RedHat platforms.
    I'm trying to execute a external process but it doesn't responds.
    when I execute the 'ps' sentence the process appears, but apparently don't work.
    If I run this proccess at the command line, it works fine.
    Can anyone offer an help?
    Thanks

    Don't forget that the output of the "Process" is not redirected to "System.out".
    --> if you want to see the output, you'll have to get the output stream of the process and dump it yourself
    InputStream processOutput = process.getOutputStream() ;
    byte buffer[] = new byte[ 512 ] ;
    while( true ) {
    int read = processOutput.read( buffer ) ;
    if( read<=0 ) {
    break ;
    System.out.write( buffer, 0, read ) ;
    }

  • Runtime exec undel linux

    Hi
    I am trying run this peace of code under linux System
    String c="/usr/java/jdk1.6.0_02/bin/java -jar \"/root/JavaApplication1/dist/JavaApplication1.jar\"  \"a\"  \"b\"  \"c\"" ;
           try {
           Process p=Runtime.getRuntime().exec(c);
          } catch (IOException ex) {
               ex.printStackTrace();
           }JavaApplication1.jar should display a frame
    but I do not have any thing
    and the exit code of the process is 0
    how can I fix this
    any help
    regards

    Have you tried including the full path for javaw in
    the Linux version?It is interesting to note that the Linux version does not have a javaw

  • Performance issue Runtime. exec("cp folder1 folder") in Linux,Weblogic.

    Using Runtime. exec() copying files from folder1 to folder2 using cp command in Linux. It will take each file copy 2 sec if we use web logic 10.3 and jrocket. if we run in Linux without web logic it takes only 0.013 sec. why it takes more time to load cp command with web logic.
    Environment
    Weblogic 10.3
    Linux 5.2
    Jrocket 1.6

    A 64 bit VM is not necessarily faster than a 32 bit one. I remember at least on suggestion that it could be slower.
    Make sure you use the -server option.
    As a guess IBM isn't necessarily a slouch when it comes to Java. It might simply be that their VM was faster. Could have used a different dom library as well.
    Could be an environment problem of course.
    Profiling the application and the machine as well might provide information.

  • Runtime.exec() does not work under Linux

    Hi,
    I have a generic application runner class that runs an external
    program and redirects stdout/stderr to a buffer/file.
    While everythings works just fine under Windows, I get the
    following exception under Linux trying to run the Java interpreter
    'java':
    java.io.IOException: "/usr/lib/SunJava2-1.3.1/jre/bin/java": not found
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:139)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:546)
    at java.lang.Runtime.exec(Runtime.java:413)
    I have checked that the file /usr/lib/SunJava2-1.3.1/jre/bin/java
    exists.
    Any help appreciated!
    Marc

    can I ask how you solved it? I am having a problem
    with quotes just now to and it might help me!I simply tested what the current platform is and
    only used quotes under Windows.
    Marc

  • Runtime.exec(), linux and redirection

    Hi all,
    I need to exec an external command from java under linux, and have both the stderr and stdout of the command redirected to the
    stdout, so that I can capture them and keep them in synch in the java app. I've tried many combination, but I'm unable to make
    this work: only the standard output shows up. Note that I can make this work under windows.
    A java code example and a small C example to simulate the program to be invoked follows. Running the java program should show both the "messsage" and the "error" lines, but it shows only the "message" ones.
    Note that removing the apparently redoundant ">&1" doesn't solve the problem. I got a suggestion to modify the exec invocation into
    String[] cmd = { "/bin/sh", "-c", "./test1 >&1 2>&1" };
      Process p = Runtime.getRuntime().exec(cmd); but that didn't work eiter.
    Can anyone tell me where I'm wrong?
    Roberto
    ======================= class test.java ================================================
    import java.io.*;
    public class test {
      public static void main(String args[]) {
        new test();
      public test() {
        try {
          Process p = Runtime.getRuntime().exec("/bin/sh -c ./test1 >&1 2>&1")
          InputStream inStr = p.getInputStream();
          BufferedReader inBr = new BufferedReader(new InputStreamReader(inStr));
          String line;
          while((line = inBr.readLine()) != null) {
            System.out.println("line = "+line);
          try {
            p.waitFor();
          } catch(InterruptedException ex) {}
          System.out.println("process terminated with code = "+p.exitValue());
          inBr.close();
        }catch(IOException ex) {
          System.out.println("IOException : "+ex.getMessage ());
    }======================= end of class test.java ================================================
    ======================= test1 program ================================================
    #include <stdio.h>
    int main(int argc, char **argv) {
      int i;
      for(i=0; i<100; i++) {
        fprintf(stdout, "message %d\n", i);
        fprintf(stderr, "error %d\n", i);
    }======================= end of test1 program ================================================

    Redirection dosen't work with Runtime.exec(), it really dosen't have sense. Do the foolowing:
    String[] cmd = { "/bin/sh", "-c", "./test1" };
    Process p = Runtime.getRuntime().exec(cmd);
    OutputStream out = p.getOutputStream();
    //now wrte out to the file, formating as you want
    What is doene obove is execute your command, without redirection, and the obtaininh the output stream of the created process. This is "the place" where the process will write everithig it'll would write in the console if executed there.
    The handle the OutputStream as any other OutputStream, and write it to the HD or do whtever you want.
    Abraham.

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

  • How to capture output of java files using Runtime.exec

    Hi guys,
    I'm trying to capture output of java files using Runtime.exec but I don't know how. I keep receiving error message "java.lang.NoClassDefFoundError:" but I don't know how to :(
    import java.io.*;
    public class CmdExec {
      public CmdExec() {
      public static void main(String argv[]){
         try {
         String line;
         Runtime rt = Runtime.getRuntime();
         String[] cmd = new String[2];
         cmd[0] = "javac";
         cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E.java";
         Process proc = rt.exec(cmd);
         cmd = new String[2];
         cmd[0] = "javac";
         cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E";
         proc = rt.exec(cmd);
         //BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
         BufferedReader input = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
         while ((line = input.readLine()) != null) {
            System.out.println(line);
         input.close();
        catch (Exception err) {
         err.printStackTrace();
    public class E {
        public static void main(String[] args) {
            System.out.println("hello world!!!!");
    }Please help :)

    Javapedia: Classpath
    How Classes are Found
    Setting the class path (Windows)
    Setting the class path (Solaris/Linux)
    Understanding the Java ClassLoader
    java -cp .;<any other directories or jars> YourClassNameYou get a NoClassDefFoundError message because the JVM (Java Virtual Machine) can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.
    javac -classpath .;<any additional jar files or directories> YourClassName.javaYou get a "cannot resolve symbol" message because the compiler can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.

  • Runtime.exec - Too Many Open Files

    System version : Red Hat Enterprise Linux 2.4.21-47.ELsmp AS release 3 (Taroon Update 8)
    JRE version : 1.6.0-b105
    Important : the commands described below are launched from a Web application : Apache Tomcat 6.0.10
    Hello,
    I'm facing a problem already known, but appearantly never really solved ??!! ;)
    When I invoke many system commands with the 'Runtime.exec(...)' method, there are open files that are not released (I can see them with the "lsof" system command) .
    At the end, the unavoidable "too many open files" Exception.
    The lauched commands are "ssh ... " commands.
    In the topics relating to this problem, the solution is always to close all Streams / threads and to explicitely invoke the method "Process.destroy()".
    My problem is that this is what I do ! And I can't do more...
    Here is the code :
           Runtime rt = Runtime.getRuntime();
           Process process = rt.exec("ssh ...");
            // ProcessStreamHolder extends Thread and reads from the InputStream given in constructor...
            ProcessStreamHolder errorStream = new ProcessStreamHolder(process.getErrorStream());
            ProcessStreamHolder outputStream = new ProcessStreamHolder(process.getInputStream());
            errorStream.start();
            outputStream.start();
            exitValue = process.waitFor();
            try {
                errorStream.interrupt();
            } catch (RuntimeException e) {
                logger.warn("...");
            try {
                outputStream.interrupt();
            } catch (RuntimeException e) {
                logger.warn("...");
            try {
                process.getInputStream().close();
            } catch (RuntimeException e) {
                logger.warn("...");
            try {
                process.getOutputStream().close();
            } catch (RuntimeException e) {
                logger.warn("...");
            try {
                process.getErrorStream().close();
            } catch (RuntimeException e) {
                logger.warn("...");
            process.destroy();Does someone know if my code is wrong or if there's a workaround for me ?
    Thanks by advance !
    Richard.

    Don't interrupt those threads. Close the output stream first, then wait for the process to exit, then both threads reading the stdout and stderr of the process should get EOFs, so they should exit naturally, and incidentally close the streams themselves.

  • Runtime exec problem to execute a C program

    Hi,
    I've spend lot of time trying to find a solution without success...
    My aim is to run a C program from a java application under linux. My C code is the following:
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    main(int argc, char **argv){
    printf("hello world \n");
    Once compiled I run my java application wich run the binary through a runtime.exec().
    I followed the example given by
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    with the same input gobblers and threads.
    For some reason it doesn't work: nothing comes out...
    When I call "ls" instead of my binary it works perfectly!
    WHY??
    Any help would be greatly appreciated!

    Thanks for the reply.
    Yes it seems that JNI could be a solution, but it looks a bit complicated an maybe not so well adapted to my purpose.
    The executables I want to execute from my java application don't need any arguments.
    If JNI is really the only way I'll try to use it but is there any good reason why runtime exec doesn't work? It is supposed to execute any executable isn't it?
    cheers

  • Using runtime.exec to zip some files

    Hi,
    I am using runtime.exec to try to automatically zip a bunch of files on a server. However, it does not seem to be working.
    Before I execute the command, I save the zip command in a string. I then print the string to a log file, and then execute the runtime zip command. But nothing happens.
    Yet, when I copy the string from the log, and paste it in a terminal, it properly creates the zip files. So, I know I have the correct command string, it just does not seem to be working within the java application. Also, the command string uses fully qualified directories, so it is not a directory issue.
    I am using ubuntu linux.
    Any ideas?
    -Adam

    adamSpline wrote:
    Hi,
    I am using runtime.exec to try to automatically zip a bunch of files on a server. However, it does not seem to be working.
    Before I execute the command, I save the zip command in a string. I then print the string to a log file, and then execute the runtime zip command. But nothing happens. Within Runtime.exec() any command does not run in a shell and I bet you use wild cards and/or other commands to be interpreted by a shell which will not be interpreted since there is no shell. And, since you don't mention error messages or the return code, I will also bet you don't process the Process stdout , stderr and the return code properly.
    It looks to me like you have fallen for at least two for the traps in [http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html].
    >
    Yet, when I copy the string from the log, and paste it in a terminal, it properly creates the zip files. So, I know I have the correct command string, it just does not seem to be working within the java application. Also, the command string uses fully qualified directories, so it is not a directory issue.
    I am using ubuntu linux.
    Any ideas?I agree with 'masijade' - use the built in Java classes.
    >
    -Adam

Maybe you are looking for

  • Creation of User Defined Fields

    Hi all, i'm developing an add-on on SAP B! and i need to create some user fields. I've seen that if I create a user field from SAP menu, on document rows, the field is replicated on several table on the DB (watching CUFD table). If i create the user

  • Using HLEVEL Property with Multiple Hierarchies

    Hello, I am trying to use the HLEVEL property on a dimension to indent the rows different amounts. Easy stuff, except I'm doing a row expansion on hierarchy 3 (H3).  Using EVPRO(AppName, MemberID, "HLEVEL") always returns the HLEVEL from H1.  If you

  • Root file system is 100% full on server with oracle databse

    hi, This was very strange to me, i have a solaris 10 Generic_122300-03 sun4u sparc SUNW,Sun-Fire-V440, with one oracle database running on it. The daatabase guys was doing some activity and the CPU utilization was 100%. I got an update from db team t

  • Pre Form

    We are in the process of optimising the existing modules on web in our applications We have following code in the PLL library which is called in WHEN-NEW-FORM-INSTANCE. Wethe it will be of any performance gain to shift this code directly into form or

  • Sql decimal datatype

    I'm using labview 7.1 with the database connectivity toolkit to interact with a sql server.  One column is of the datatype float, but when I send 0.95, it stores 0.94999999.  I've read about this before, but trying to use numeric or decimal causes a