Runtime.exec() crashes JVM

I wrote a program that runs a Perl script repeatedly via Runtime.exec().
Q: Under what circumstances would this procedure silently crash the JVM? I am experiencing this behavior on Linux using Sun's JDK as well as IBM's. There is no error output. The program simply exits. What is causing this? And, how can it be avoided? If there is a way to recover from whatever problem is occurring, that would be ideal.

Thanks jschell! Your input is helpful.
I suspect that case #4 is in play here. When I run my program with the "-Xrs" switch, "Terminated" is outputted just before the JVM exits. Is there any way to intercept the signal to terminate from the child process before the JVM exits?
NOTE: I am not running Runtime.exec() concurrently and I am explicitly destroying each Process after process.waitFor(). Also, I tend to watch the linux "top" output to confirm that only one Perl process is running at a time. I have tried various versions of a "runCommand" method. The current version spawns no additional threads:
public static int runCommand(String[] command) throws InterruptedException, IOException
          ProcessBuilder builder = new ProcessBuilder(command);
          builder.redirectErrorStream(true);
          Process process = builder.start();
          InputStream input = null;
          InputStream error = null;
          OutputStream output = null;
          BufferedReader reader;
          String line;
          try     {
               input = process.getInputStream();
               error = process.getErrorStream();
               output = process.getOutputStream();
               reader = new BufferedReader(new InputStreamReader(input));
               while ((line = reader.readLine()) != null)
                    System.out.println(line);
               return process.waitFor();
          finally
               close(output);
               close(error);
               close(input);
               process.destroy();
          }

Similar Messages

  • Runtime.exec and ServerSocket for IPC...blocking problems

    I have built an IDE for assembling/deploying web applications.
    I am supporting a 'test' mode in the IDE where a compiled 'solution/application' is executed in a separate vm from the IDE using Runtime.exec. For the whole sandbox thing. Don't want a wayward application crashing my IDE.
    Naturally I want a way to communicate start/stop from the IDE to the running application. So sockets are my only choice. Calling process.destroy from my IDE won't invoke a shutdownhandler in the generated application's vm, and I want an orderly shutdown as the generated applications open resources/etc.
    When I execute the generated application from within the IDE the thread code that creates a server socket blocks in the ServerSocket constructor...why?
    When I execute the solution using 'java' outside of my IDE, I can set up a server socket and all works fine.
    My IDE is NEVER creating server sockets waiting for client connects...only the generated application does this. So it isn't a case of the IDE already listening for requests on the same port as the server/generated application.
    Proving the above is that I can manually start my generated application, start my ide, then invoke the menuitem from the IDE that writes a 'close' byte to the client's socket...and the running application DOES shut down.
    Any ideas?

    I have decided on a different approach.
    At first I thought...ok I have the ServerSocket on the wrong 'side'. I then put the ServerSocket code in the always-running IDE and the Socket code on the running/exec'd application. But still a hang on the running application when constructing the Socket.
    I decided instead to call Process.destroy on the running app.
    Given that generated app is running in a separate vm, when it shuts down via process.destroy from the ide...although vm shutdown hooks aren't called...I guess it's ok since a destroy of the vm will release all resources. Not as clean as I'd like though.
    Additionally, I cannot determine 'true' start of application as no socket notification can be done. I merely determine start after a Runtime.exec of jvm process. Subsequent errors in startup will merely be determined by the IDE in process.waitFor or process.exitValue.
    I was getting a wierd socket error when attempting my prior solutions...and not a lot on the web regarding this subject...all relevant posts seemed to be in German/from Germany. Odd. Would need my wife to translate! Mein gott!
    I guess I could've communicated from ide to Runtime.exec'd application via a generated file in filesystem...but this seemed cheesy. Sockets should've been used for ipc between java vms...or so I thought.

  • Tidal abends with error message: Jvm call Runtime.exec() returned null

    just wandering if this error "Jvm call Runtime.exec() returned null  Command[chmod 777] launch failed." is a tidal error and not a job command error returned from the OS server.
    thanks,
    warren

    I'm having the same problem...
    Have you been able to solve your problem yet?

  • JVM spawning mysterious child process of itself using Runtime.exec()

    Hello, I'm not sure if this is how this is supposed to work but I have a java application that monitors legacy c programs and after a period of time (its intermittent), I'll see a duplicate jvm process running the same classpath, classname as a child of the java application monitor. This behaviour can be reproduced with the following simple class running on either solaris 9 or 10 using 1.6.0_03-b05:
    public class Monitor {
    Process procss;
    public Monitor() {
    try {
    Runtime runtime = Runtime.getRuntime();
    for (int i = 0; i < 10000; i++) {
    System.out.println("execing command ls -l.");
    procss = runtime.exec("ls -l");
    procss.waitFor();
    catch (Exception e) {
    e.printStackTrace();
    public static void main(String[] args) {
    new Monitor();
    Using java -classpath ./ Monitor to run it. While this is running, at intermittent times doing a ps -ef you will see a duplicate jvm running whose parent process is the one that was started on the command line. Ie:
    UID PID PPID etc
    user 17434 10706 .... java -classpath ./ Monitor (the one I put running)
    user 27771 17434 .....java -classpath ./ Monitor (intermittently started)
    in another window I'll run the following shell script that will output the processes when a duplicate java process gets started as they don't seem to run very long (on my production system they will occasionally get hung up until I manually kill them):
    #!/usr/bin/ksh
    while ((1 == 1))
    do
    ps -ef | grep "Monitor" | grep -v grep > /tmp/test.out
    VAL=`cat /tmp/test.out | wc -l`
    if (($VAL != 1))
    then
    echo "Duplicate java process started"
    cat /tmp/test.out
    fi
    done
    It takes roughly 30 seconds before I start to see duplicate jvms starting to run. The concern is that is the new jvm instance running the Monitor class? Eventually on my production system the real application will have a child or 2 linger indefinetly, and threads will be deadlocked. Once I kill these child java processes, everything is back to normal. This doesn't seem to occur with the above java class but will show the duplicate child jvm's start to run after a bit.

    This is true for Solaris and Linux. Sun's implementation does a fork. A lot of people who have very large memory java applications wish there was a way to create a process from Java that doesn't involve copying the parent process. As far as I know your stuck.
    A workaround: Use jms, rmi, sockets, or files to communicate with a low memory footprint java application whose sole purpose is to spawn child processes.

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

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

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

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

  • Using Runtime.exec on a Unix System

    hi,
    I have a web service which executes a command line process 'Runtime.exec(command)'. When the server starts to go on a high load I start to get "IOException: Not Enough Space" which I understand means that I am running out of swap space. No problem as I can increase the swap space to cope with demand. The problem is that I have read that when JVM attempts a fork on a Unix system it temporarily creates a new JVM with the same space requirements as the app server JVM. So if I set my app server to require 1GB memory, I am likely to need to set up swap so that it has 1GB * Number of Parallel Processes. I need to know if this is correct. Our application today does not limit the number of Runtime.exec commands which can be run in parallel and if the above is true we are going to have a problem ensuring we don't run out of memory.
    Can any one verify this or suggest other solutions to the problem?
    Thanks
    Stephen

    hi,
    Yes, very helpful jwenting! Problem is that we are working with legacy systems where we have few other options. If you can give any positive input it's not worth leaving your option at all.
    Thanks
    Stephen

  • Increasing memory used by java process when calling Runtime.exec()

    Hi everyone!
    I'm running a servlet Oracle iAS 9i, Jserv. It receives an image posted by a user and does a System.exec() which performs a call to convert (an image processing utility included in ImageMagick).
    After a few hours, java process start taking more and more RAM, until it crashes with an error like this:
    Memory: 5394008 free of 134217728 total. (I log this myself)
    Exception: java.io.IOException: Not enough space
    java.lang.UNIXProcess.forkAndExec(), line -2.
    java.lang.UNIXProcess.<init>(), line 54.
    java.lang.Runtime.execInternal(), line -2.
    java.lang.Runtime.exec(), line 553.
    ImageProcessor.convert(), line 235.
    ImageProcessor.createItemPics(), line 124.
    Uploader.doPost(), line 69.
    As you can see, this is not an OutOfMemoryError, but something else in connection with O/S.
    This is not related to hard disk space, since there is a lot of free space in every filesystems
    After restarting the webserver, everything goes back to normal and start increasing RAM again.
    Is there anything I can do? Any help will be gratly appreciated... Thanks!!!
    Dani.-

    Have you had any solutions to this pal?
    I am also suffering. I tried closing the processes by:
    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec("/opt/sta_rpms.sh " + sFileName);
    proc.waitFor();
    proc.getInputStream().close();
    proc.getOutputStream().close();
    proc.getErrorStream().close();
    proc.destroy();
    proc = null;
    but still after like a day...Though our codes are not alike, it sounds like the same reason.
    Cheers!

  • Need info about Runtime.exec

    Hello, I have a non program specific question about how Runtime.exec works. First off assume that I handle all my input streams and output streams correctly, and I am not worried about inter process communication. The question is, when I use Runtime.getRuntime().exec(cmd[],pth[],dir) does the JVM that is running the code that calls it live until the spawned process dies, or can it die without waiting for the execed process to die? I am trying to write an app that can spawn a new copy of itself that is completely independent from the original process, and may live on long after the original is no longer needed. To ensure proper resource management I need to know that the JVM that launches the new process does not have to wait for the new process to die prior to completely cleaning itself up.
    Does that make sense?
    Any suggestions, ideas, questions?
    Thanks in advance for the help.
    Message was edited by:
    elixic

    Thank you all who gave useful input. I had done some reading on this already and could not find a definite answer on weather or not the calling JVM can properly dispose of itself prior to the process it called being disposed of.
    The answer it seems is dependent on context. In windows, and from a GUI app, it looks like the calling JVM can die any time it wants too. A command line app on the other hand seems to have to wait for the app it called to die first. I have not tested it on other OS's but I am sure it varies by OS as well. I would not even be surprised if it varies by JVM.
    So the short answer to my question that you all helped me find is this, It varies by context.
    Thanks again for the help.
    Isaac

  • Use of Runtime.exec

    I know that there are security concerns with making a call to the java.lang.Runtime's
    exec method, but are there any performance concerns? When an exec call is made
    by an object within the application server does the forking of a new process to
    execute the command cause a process equivalent in size to the application server
    to be generated? Our application server process is quite large, so this would
    be an expensive operation.

    The OS-level semantics of Runtime.exec are tied to JVM implementation (that's why
    it doesn't work on most releases of the MacOS for example)...
    Runtime.exec has a lot of not-so-intuitive handholding associated with it. For
    example, did you know that on most flavors of Windows JVMs, you have to read out
    of the STDOUT and STDERR streams, or the process you invoked will hang when their
    buffer fills up? JavaWorld ran an article a while back with all the details on
    this-- you can write a stream gobbler to suck up anything and send it to /dev/null
    to avoid problems.
    "Ash Beitz" <[email protected]> wrote:
    >
    I know that there are security concerns with making a call to the java.lang.Runtime's
    exec method, but are there any performance concerns? When an exec call
    is made
    by an object within the application server does the forking of a new
    process to
    execute the command cause a process equivalent in size to the application
    server
    to be generated? Our application server process is quite large, so this
    would
    be an expensive operation.

  • Question about Runtime.exec

    Rob,
    Thanks for your help.
    I asked a question about a weird Exception on Nov 14, and you told me that I am
    using Runtime.exec to start an external process, and that process is crashing.
    I am a green-hand on Weblogic, and I am trying to enhancing a project developped
    by another person, so I am not familiar with some concepts yet.
    Could you please give me some simple explanation about Runtime.exec and external
    process?
    I found two methods that uses "Runtime" from two classes as following, could you
    help me to see whether or not there is something wrong with the usage of Runtime?
    Thank you very much.
    private int runShellCommand(String command) {
    int exitVal = -1;
    try {
    File runDir = new File(runDirectory);
    String[] env = new String[0];
    Runtime rt = Runtime.getRuntime();
                   double start = System.currentTimeMillis();
    Process proc = rt.exec(command, env, runDir);
    // Capture output in separate thread
    ThreadedStreamReader error = new ThreadedStreamReader(proc.getErrorStream(),
    "ERROR");
    ThreadedStreamReader output = new ThreadedStreamReader(proc.getInputStream(),
    "OUTPUT");
    error.start();
    output.start();
    exitVal = proc.waitFor();
    if (logger.isDebugEnabled()) {
         double runtime = (System.currentTimeMillis() - start) / 1000.0;
         logger.info("run " + runId + " " + command + " finished in " + runtime
    + " seconds");
    } catch (IOException e) {
    logger.fatal("DOE-2 failed \n" + e.getMessage());
    } catch (InterruptedException e) {
    e.printStackTrace();
    return exitVal;
    public static void main(String[] args) throws Exception, InterruptedException
    final Doe2MessageServer server = new Doe2MessageServer();
    while(!connected) {
    Thread.sleep(1000);
    logger.info("Attempting to start JMS service ...");
                   try {
              server.init();
                   } catch (Exception ex) {
    // shutdown hook to close JMS connection
    Runtime.getRuntime().addShutdownHook(
    new Thread() {
    public void run() {
    server.finalize();
    server.receiveMessage();

    Runtime.exec is a J2SE API. It's not really specific to WLS.
    You can read about it here:
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Runtime.html
    It looks like you are starting a JMS Server in a separate process and
    that process is crashing.
    (You could of course just use WLS's JMS Server instead :>)
    -- Rob
    Iris Qu wrote:
    Rob,
    Thanks for your help.
    I asked a question about a weird Exception on Nov 14, and you told me that I am
    using Runtime.exec to start an external process, and that process is crashing.
    I am a green-hand on Weblogic, and I am trying to enhancing a project developped
    by another person, so I am not familiar with some concepts yet.
    Could you please give me some simple explanation about Runtime.exec and external
    process?
    I found two methods that uses "Runtime" from two classes as following, could you
    help me to see whether or not there is something wrong with the usage of Runtime?
    Thank you very much.
    private int runShellCommand(String command) {
    int exitVal = -1;
    try {
    File runDir = new File(runDirectory);
    String[] env = new String[0];
    Runtime rt = Runtime.getRuntime();
                   double start = System.currentTimeMillis();
    Process proc = rt.exec(command, env, runDir);
    // Capture output in separate thread
    ThreadedStreamReader error = new ThreadedStreamReader(proc.getErrorStream(),
    "ERROR");
    ThreadedStreamReader output = new ThreadedStreamReader(proc.getInputStream(),
    "OUTPUT");
    error.start();
    output.start();
    exitVal = proc.waitFor();
    if (logger.isDebugEnabled()) {
         double runtime = (System.currentTimeMillis() - start) / 1000.0;
         logger.info("run " + runId + " " + command + " finished in " + runtime
    + " seconds");
    } catch (IOException e) {
    logger.fatal("DOE-2 failed \n" + e.getMessage());
    } catch (InterruptedException e) {
    e.printStackTrace();
    return exitVal;
    public static void main(String[] args) throws Exception, InterruptedException
    final Doe2MessageServer server = new Doe2MessageServer();
    while(!connected) {
    Thread.sleep(1000);
    logger.info("Attempting to start JMS service ...");
                   try {
              server.init();
                   } catch (Exception ex) {
    // shutdown hook to close JMS connection
    Runtime.getRuntime().addShutdownHook(
    new Thread() {
    public void run() {
    server.finalize();
    server.receiveMessage();

  • Running java process in a while loop using Runtime.exec() hangs on solaris

    I'm writting a multithreaded application in which I'll be starting multiple instances of "AppStartThread" class (given below). If I start only one instance of "AppStartThread", it is working fine. But if I start more than one instance of "AppStartThread", one of the threads hangs after some time (occasionaly). But other threads are working fine.
    I have the following questions:
    1. Is there any problem with starting a Thread inside another thread?. Here I'm executing the process in a while loop.
    2. Other thing i noticed is the Thread is hanging after completing the process ("java ExecuteProcess"). But the P.waitFor() is not coming out.
    3. Is it bcoz of the same problem as given in Bug ID : 4098442 ?.
    4. Also java 1.2.2 documentation says:
    "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. "
    I'm running this on sun Solaris/java 1.2.2 standard edition. If any of you have experienced the same problem please help me out.
    Will the same problem can happen on java 1.2.2 enterprise edition.?
    class AppStartThread implements Runnable
    public void run()
    while(true)
    try
    Process P=Runtime.getRuntime().exec("java ExecuteProcess");
    P.waitFor();
    System.out.println("after executing application.");
    P.destroy();
    P = null;
    System.gc();
    catch(java.io.IOException io)
    System.out.println("Could not execute application - IOException " + io);
    catch(java.lang.InterruptedException ip)
    System.out.println("Could not execute application - InterruptedException" + ip);
    catch (Exception e)
    System.out.println("Could not execute application -" + e.getMessage());

    I'm writting a multithreaded application in which I'll
    be starting multiple instances of "AppStartThread"
    class (given below). If I start only one instance of
    "AppStartThread", it is working fine. But if I start
    more than one instance of "AppStartThread", one of the
    threads hangs after some time (occasionaly). But other
    threads are working fine.
    I have the following questions:
    1. Is there any problem with starting a Thread inside
    another thread?. Here I'm executing the process in a
    while loop.Of course this is OK, as your code is always being run by one thread or another. And no, it doesn't depend on which thread is starting threads.
    2. Other thing i noticed is the Thread is hanging
    after completing the process ("java ExecuteProcess").
    But the P.waitFor() is not coming out.This is a vital clue. Is the process started by the Runtime.exec() actually completing or does the ps command still show that it is running?
    3. Is it bcoz of the same problem as given in Bug ID :
    4098442 ?.
    4. Also java 1.2.2 documentation says:
    "Because some native platforms only provide limited
    ed 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. "These two are really the same thing (4098442 is not really a bug due to the reasons explained in the doc). If the program that you are exec'ing produces very much output, it is possible that the buffers to stdout and stderr are filling preventing your program from continuing. On Windows platforms, this buffer size is quite small (hundreds of characters) while (if I recall) on Solaris it is somewhat larger. However, I have seent his behavior causing problem on Solaris 8 in my own systems.
    I once hit this problem when I was 'sure' that I was emitting no output due to an exception being thrown that I wasn't even aware of - the stack trace was more than enough to fill the output buffer and cause the deadlock.
    You have several options. One, you could replace the System.out and System.err with PrintStream's backed up by (ie. on top of) BufferedOutputStream's that have large buffers (multi-K) that in turn are backed up by the original out and err PrintStream's. You would use System.setErr() and System.setOut() very early (static initializer block) in the startup of your class. The problem is that you are still at the mercy of code that may call flush() on these streams. I suppose you could implement your own FilterOutputStream to eat any flush requests...
    Another solution if you just don't care about the output is to replace System.out and System.err with PrintStreams that write to /dev/nul. This is really easy and efficient.
    The other tried and true approach is to start two threads in the main process each time you start a process. These will simply consume anything that is emitted through the stdout and stderr pipes. These would die when the streams close (i.e. when the process exits). Not pretty, but it works. I'd be worried about the overhead of two additional threads per external process except that processes have such huge overhead (considering you are starting a JVM) that it just won't matter. And it's not like the CPU is going to get hit much.
    If you do this frequently in your program you might consider using a worker thread pool (see Doug Lea's Executor class) to avoid creating a lot of fairly short-lived threads. But this is probably over-optimizing.
    Chuck

  • Runtime.exec lifecycle

    I am trying to execute a client using the following code below. It works fine when i run as stand alone java program. I am familiar with the javaworld article "When Runtime.exec() won't" ...
    Process p = Runtime.getRuntime().exec("\"c:\a b\\client.exe\" "\"some param\"""); //   "c:\a b\client.exe" "some param"
                InputStream in = p.getInputStream();
                InputStream err = p.getErrorStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String line = null;
                while ((line = br.readLine()) != null) {           }
                in.close();            br.close();
                br = new BufferedReader(new InputStreamReader(err));
                while ((line = br.readLine()) != null) {            }
                p.destroy();But when I incorporate it to a web application using jrun it crashes in windows, shows the debug dialog. I don't get any exceptions.
    Any clues?

    As has already been pointed out, you do need to follow the recommendations in the 'traps' article but you seem to have ignored two of them.
    First, you don't read stdout and stderr in separate threads. You can use the control thread to read one of them and a separate thread to read the other. Even better, if your really don't care about the content of stdout and stderr then use ProcessBuilder and redirect stderr to stdout and read stdout as you currently do.
    Second, you don't wait for the process to terminate. Even worse, you destroy() it! Don't do this. This is possibly why the process crashes! Always wait for the process to complete and always check the exit code.
    Now not part of the 'traps' article but a bit of advice - when debugging a Runtime.exec() problem or a ProcessBuilder problem ALWAYS write the stdout and stderr out somewhere. It is a very very very useful bit of diagnostic information.

  • Runtime.exec() under a specific user account ???

    Hi there,
    I cann't figure out how to run a script on Unix under a specific user account using the Runtime.exec(). Currently whoever run the java program, the script is ran under that user account.
    The code is like:
    public class javarun {
    public static void main(String[] arg) {
    String str = "myunixscript";
    // check the arg[1] to decide the appropriate environment.
    Runtime r = Runtime.getRuntime();
    try {
    Process pr = r.exec(str);
    pr.waitFor();
    int exitstatus = pr.exitValue();
    } catch (...) {...}
    We have two user accounts: unixusr1 and unixusr2. Now I need to have unixusr1 run the java program ( ie. unixusr1$ java javarun), while the "myunixscript" be executed under unixusr2. One further step is to the unix account name as a parameter so the unixscript could be run under different account.
    Any help will be highly appreciated. Thanks.
    Edward.

    I'm not sure if I have a solution, but here are some questions:
    a) have you tried writing additional input to the OutputStream of the process? Although I have not tried it, I would imagine that Process.getOutputStream() exists for commands that require the invoking resource to send additional input to the process- like an su command that requires a password check.
    b) can you just write a shell script that takes the needed information as an argument. That is, write a shell script that takes the username and password as an argument and then you can use Runtime like,
    Runtime.exec("myScript", new String[] { "hisId", "hisPasswd" });Obviously, you would need to think through the security concerns of such a script, but, if it complies with the security structure of your environment, it might allow you to avoid the problem by using the shell script to invoke the destination command with the proper UID and password, rather then using the JVM to invoke it. Basically, the script becomes a proxy for the JVM to invoke that command.

  • Runtime exec IOException issues

    Hello,
    I have spent two 10 hours days on this problem with countless search permutations and peering into everything from kernel source to java source. Unfortunately, I am not coming up with useful results.
    Overview:
    I have a very large java application (Apache solr) running on a server with 12GB memory. Without going into too much detail, this application at a point will use a Runtime exec call to fire off a bash shell script. Over time, however, I end up with an IOException "Cannot allocate memory." (More info and stack trace below.)
    That application aside I have been able to reproduce this by varying the -Xms and -Xmx jvm parameters with confusing results using the simple program below:
    //Use with various -Xms and -Xmx arguments to produce
    //IOException on call to Runtime.exec()
    import java.io.*;
    public class DoRuntime {
       public static void main(String args[]) throws IOException {
          Runtime runtime = Runtime.getRuntime();
          long total = runtime.totalMemory();
          long max = runtime.maxMemory();
          long free = runtime.freeMemory();
          System.out.println("total: " + total);
          System.out.println("max: " + max);
          System.out.println("free: " + free);
          Process process = runtime.exec("/bin/ls");
          InputStream is = process.getInputStream();
          InputStreamReader isr = new InputStreamReader(is);
          BufferedReader br = new BufferedReader(isr);
          String line;
          while ((line = br.readLine()) != null) {
             System.out.println(line);
    }Here are some sample runs:
    RUN1
    rwoodrum@util1wad:~/tmp$ java DoRuntime
    total: 188743680
    max: 954466304
    free: 187759312
    DoRuntime.class
    DoRuntime.java
    rwoodrum@util1wad:~/tmp$
    RUN2
    rwoodrum@util1wad:~/tmp$ java -Xms10g -Xmx10g DoRuntime
    total: 10290069504
    max: 10290069504
    free: 10236381080
    Exception in thread "main" java.io.IOException: java.io.IOException: Cannot allocate memory
            at java.lang.UNIXProcess.<init>(UNIXProcess.java:148)
            at java.lang.ProcessImpl.start(ProcessImpl.java:65)
            at java.lang.ProcessBuilder.start(ProcessBuilder.java:451)
            at java.lang.Runtime.exec(Runtime.java:591)
            at java.lang.Runtime.exec(Runtime.java:429)
            at java.lang.Runtime.exec(Runtime.java:326)
            at DoRuntime.main(DoRuntime.java:14)
    rwoodrum@util1wad:~/tmp$
    RUN3
    rwoodrum@util1wad:~/tmp$ java -Xms10g -Xmx11g DoRuntime
    total: 10290069504
    max: 10498867200
    free: 10236381080
    DoRuntime.class
    DoRuntime.java
    rwoodrum@util1wad:~/tmp$-----
    (FWIW, I get the same results replacing /bin/ls with something as lightweight as /bin/true.)
    As can be seen in the above output of RUN2, I have set a fixed heap size of 10GB. The jvm seems content with that heap size, but when it goes to exec the child process it becomes rather unhappy. From this I would perhaps conclude that ultimately inside the call to forkAndExec (libjava.so) the call to fork() failed with an ENOMEM. (As a side note, an strace on the process doesn't actually ever show a fork, only a call to clone - which utilizes a fork eventually - more on clone below.)
    The results of RUN3, however, seem to imply that the problem is within the jvm itself. In RUN3, I set the initial heap allocation to 10GB, as in RUN2, but I set the maximum at 11GB. One would think (or at least I would) that if the fork in RUN2 failed that it would certainly fail in the case of RUN3. It doesn't.
    The manpage of clone indicates that the child process will "share parts of its execution context with the calling process". Indeed, if I'm reading it correctly, it indicates that the child process stack (among other things) is housed in the parent process address space.
    Could it be that by setting this very large, fixed heap size as in RUN2, there is no room for the jvm to "maneuver" and properly handle the effort of the Runtime.exec? The fact that RUN3 is successful is what has made me think something like this, but I am by far an expert on how the jvm would handle that sort of thing.
    In our production setup of this application, I adjusted the Xmx setting to be something larger than the Xms setting. This worked for a period of time, but eventually produced the same results. I suspect over time the heap simply increased toward the max and again the jvm couldn't do its thing when it came time to RunTime.exec. The fact that this happens on the trivial Runtime.exec program would seem to rule out a memory leak of the production application.
    Ultimately something fishy is going on with memory, but with seemingly contradictory results, I am at a loss of where the problem lies.
    If I have omittied any potentially relevant information, please let me know. Any thoughts are greatly appreciated.
    Some basic system information:
    rwoodrum@util1wad:~/tmp$ free
                 total       used       free     shared    buffers     cached
    Mem:      12304936   12200376     104560          0     337276    7082508
    -/+ buffers/cache:    4780592    7524344
    Swap:      2097144         32    2097112
    rwoodrum@util1wad:~/tmp$ uname -a
    Linux util1wad 2.6.18-4-amd64 #1 SMP Mon Mar 26 11:36:53 CEST 2007 x86_64 GNU/Linux
    rwoodrum@util1wad:~/tmp$ java -version
    java version "1.5.0_10"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_10-b03)
    Java HotSpot(TM) 64-Bit Server VM (build 1.5.0_10-b03, mixed mode)-ryan woodrum

    I've continued to investigate this with my discoveries below. I've found some more interesting nuances, but am still not satisfied with the explanation of what is going on here. For time reasons, I've capitulated to a somewhat lame workaround.
    The test run in the 1.6.0 jvm environment is somewhat revealing in that it confirms that the eventual call to fork (I'm kind of guessing it's the fork call here) is returning an ENOMEM. The 1.5.0 jvm was not returning the actual errno from the call in the JNI code. Checking out $linux_src/include/asm-generic/errno-base.h indeed enumerates ENOMEM to 12.
    When I saw this, I started looking at the memory commit inside of /proc/meminfo to see what was going on when I would launch the jvm with the varying Xmx and Xms parameters. Somewhat unsurprisingly at this point, when I would run with large a large heap, the Committed_AS would skyrocket by a proportion roughly equal to the fixed heap size. (See here http://lwn.net/Articles/28345/ for an definition of Committed_AS and other /proc/meminfo fields.)
    With the above information in hand, I wanted to confirm without a doubt that the kernel was the thorn in my side. So on a test system I started to play around with the vm_overcommit feature - see $linux_src/Documentation/vm/overcommit-accounting for definitions of modes 0,1, and 2). Sure enough, toying with these modes I was able to alter the behavior of launching the jvm. I switched from the default heuristic mode (0) to an "always overcommit" mode and it would launch and sucessfully fork and exec every time. No surprise there.
    What IS surprising, however, is that if, under the default heuristic mode, I specify the jvm parameters differently it will sucessfully run and fork and exec the subprocess. It seems odd to me that at the OS level, specifying `java -Xms4g -Xmx4g` will cause the subprocess fork to fail but specifying `java -Xms4g -Xmx5g` will NOT cause the fork to fail. Running with the latter parameters shows the exact same Committed_AS spike. This all begs the question(s): What's the difference? With a min heap size set to 4g (or whatever) on the both jvm runs, how does a jvm parameter (especially one that allows MORE growth of the heap) impact this call to fork? One variable in the picture at this point that I'm unsure of is the strace call to clone(). I don't know what this could be doing to make things behave differently.
    So as I noted, above, I have a relatively lame workaround. Blindly add more swap to increase the CommittedLimit inside the kernel. It'll never get used, it's a waste of space, and, perhaps most importantly, on principal it just rubs me the wrong way.
    -ryan woodrum

Maybe you are looking for

  • Of the version attribute of a HelpSet tag

    Okay, I admit to being somewhat stumped here. Is there any way to access the value of the version attribute of the helpset element (or indeed, any of the version attributes of any of the various index, content & map files)? I'm trying to version an a

  • Computer constantly restarting due to an error - 2010 Macbook Pro

    Hi guys, so this is my first post here in the service community so please let me know if I need to provide any additional information. Anyway, on to the issue.  So this has been going on for a while now, but in the last month or so it has really gott

  • Dynamic URL for Recv HTTP (Adapter spec attribute enabled)

    Hi, I need to have a dynamic URL for one of my cases been worked. the URL is httlp://:<host>/perform/XTA?serv=*&action=start the event "action" can accept either start/stop or restart. i wanna to control this dynamically and went for recv http enable

  • Have just installed 10.6 on a separate partition...

    and want iTunes to use my existing music library from the (still existing) previous partition, so I can sync my iPhone without wiping it. I've "transferred purchases" so any music I bought off iTunes and all apps etc are on the new install, but none

  • Job Scheduling question

    If I request a ob to be scheduled with the command: dbms_job.submit() How can I monitor the status of the job Which table do I need to perform a select on ? Thanks