Running a process within a java program

Hi
I have code that runs a process for performance monitoring on an installed system. When I run the code standalone as below, it runs fine. If I include the code below inside another java program, the process fails to execute and the status returned is non-zero (failed to execute).
The process requires the PATH and LD_LIBRARY_PATH to be set which seem to be set correctly when i print them out. So, I am not sure why the process doesnot run when included within another running java program.
Can someone please point out what I maybe missing?
Thanks!!
public class RunPerf
  private static final String CLASS_NAME = "RunPerf"; private static Process proc = null;
public static void main(String[] args)
    String INSTALLPERF_SAW_UNIX_COMMAND = "sawexe" + " " + "-perf";
         StringBuffer path1 = new StringBuffer(30);StringBuffer ldlibpath1 = new StringBuffer(30);
    System.setProperty("user.home", "/home/user");
    StringBuilder commandToExecute = new StringBuilder();
   commandToExecute.append(System.getProperty("user.home"));
   commandToExecute.append(File.separator);
   commandToExecute.append("web");
   commandToExecute.append(File.separator);
   commandToExecute.append("bin");
   commandToExecute.append(File.separator);
     String path = System.getProperty("user.home")+"/server/bin/" + File.pathSeparator + System.getProperty("user.home")+ "/web/bin";
       path1.append( path );
       path1.append( File.separator );
       path1.append( System.getProperty("java.library.path") );
       path1.append( File.separator );
      String env_value = null;
     String[] ldargs = {"LD_LIBRARY_PATH"};
     for (String env: ldargs) {
            env_value = System.getenv(env);
         System.out.println("LD_LIBRARY_PATH value before setting property= " + env_value);
            if (env_value != null) {
           String newldlibpath = System.getProperty("user.home")+ "/server/bin/" + File.pathSeparator + System.getProperty("user.homee")+ "/web/bin" ;
            ldlibpath1.append(newldlibpath);
            ldlibpath1.append(File.separator);
               ldlibpath1.append(env_value);
               ldlibpath1.append( File.separator);
                System.out.format("%s=%s%n", env,ldlibpath1.toString());
            } else {
                System.out.format("%s is not assigned.%n", env);
             commandToExecute.append(INSTALLPERF_SAW_UNIX_COMMAND);
               String[] envp =   { "USER_HOME =" + "/home/user",          "PATH=" + path1.toString(), "LD_LIBRARY_PATH=" + ldlibpath1.toString() };
           int status = executeCommand1(commandToExecute.toString(), envp,null);
               if(status != 0){
                      System.out.println("Unable to run perf Unix") ;
     public static int executeCommand1(String command,String[] envp, Logger logger) {
        String METHOD_NAME = "executeCommand1";
        if (logger == null) { logger = Logger.getAnonymousLogger();}
        logger.entering(CLASS_NAME, METHOD_NAME, new Object[] { command, envp});
        Runtime runtime = Runtime.getRuntime();
        runtime.addShutdownHook(new Thread() {
                    public void run() {
                        if (proc != null) {     try {  proc.destroy();  if (proc != null) { proc.destroy();  }
                            } catch (Exception e) {
                                e.printStackTrace(); }      }      }     });               
                       int retVal = 0;
      File cwd = new File(System.getProperty("user.home")+ "/web/bin/");               
                       try {
                           if (envp != null) {   proc = runtime.exec(command, envp,cwd); }
                                   else {  proc = runtime.exec(command); }
                           Thread t_err =        new Thread(new StreamReader(proc.getErrorStream()));
                           t_err.start();
                           Thread t_in =     new Thread(new StreamReader(proc.getInputStream()));
                           t_in.start();
                           retVal = proc.waitFor(); } catch (IOException e) {        retVal = -1;   logger.severe("IOException");      }
                                 catch (Exception e) { retVal = -1;        logger.severe("Exception");                  }
                 logger.exiting(CLASS_NAME, METHOD_NAME, retVal);
                 return retVal;
static class StreamReader implements Runnable {
        InputStream in;
        public StreamReader(InputStream genericStream) {   in = genericStream;   }
        public void run() {
            try {
                String strTemp = null;
                BufferedReader buffReader = new BufferedReader(new InputStreamReader(in));
                while ((strTemp = buffReader.readLine()) != null) {
                    System.out.println(strTemp);                }
            } catch (Exception e) {               e.printStackTrace();            }        }    }}

Either set up a script before the program runs or have the
program write a script file which contains the statements
that need to be executed. Then you will be able to
execute the script with a call to
Runtime.getRuntime().exec()Mark

Similar Messages

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

  • Executing a Java Program from within a Java Program

    I need to execute the following Java Program from withing another Java Program. The office toolbar command line is
    D:\WINDOWS\system32\java.exe -cp E:\Development\Eclipse\UpdateServer\Classes -server -showversion UpdateServer
    I can find no combination of ProcessBuilder commands, including those that include "Cmd.exe /c" that will make this program run from within another Java Program. All the examples I can find only show how to run Windows *.exe programs. I keep getting error 123 from ProcessBuilder.start(), but I can find no documentation for error 123.

    Assuming your code didn't get mangled by the forum
    (it's missing one "), it may be that your "-cp
    E:\\Develop.." argument is getting quoted as it has a
    space in it; try passing "-cp" and "E:\\Develop..."
    as two arguments.That worked; specifically the following tested OK:
    ProcessBuilder pb = new ProcessBuilder("D:\\WINDOWS\\System32\\Java.exe", "-cp", "E:\\Development\\Eclipse\\UpdateServer\\Classes\\", "-server", "-showversion", "UpdateServer" );
    pb.directory(new File("E:\\Development\\Eclipse\\UpdateServer\\Classes\\"));
    try{
         Process p = pb.start();
         InputStream is = p.getErrorStream();
         InputStreamReader isr = new InputStreamReader(is);
         BufferedReader br = new BufferedReader(isr);
         String line;
         while ((line = br.readLine()) != null)
              System.out.println(line);
         p.waitFor();
    }catch(IOException ioe){
    I was sure I tried that exact same code before, and it did not work, but now it does, at least at the top level (when it is in main of a test program). I will have to wait to try it until later when it is buried deep in a subroutine.

  • How does one run a *.exe with a Java program?

    Hi,
    I'm looking for a way to run an executable (*.exe) or batch file (*.bat) from within a Java program.
    Any suggestions, leads, or examples appreciated.
    Thanks!

    Runtime.getRuntime.exec("pathTo/yourapp.exe");
    For any type of interpreted scripts, the interpreter should be added:
    Runtime.getRuntime().exec({ "command.com", "mybat.bat"});
    or
    Runtime.getRuntime().exec({"/bin/sh", "configure.sh"});

  • Compiling one java file within another java program

    Hi all,
    I want to compile one java file say one.java within a java program say second.java.. i simply have no idea as how to proceed ..pls help!!

    http://onesearch.sun.com/search/onesearch/index.jsp?qt=dynamically+compile&subCat=siteforumid%3Ajava31&site=dev&dftab=siteforumid%3Ajava31&chooseCat=javaall&col=developer-forums
    Just to give you an idea.

  • Start a WS application from within a java program

    Hi,
    I need to start a WebStart application from within a java program. Therefore I develeoped a class which starts javaws.exe within its main-method like this:
    try {
    Runtime.getRuntime().exec(
    "c:\\java web start\\javaws.exe http://a.b/c.jnlp"
    } catch (Exception e) {
    e.printStackTrace();
    And that did not work. Java Web Start tries to start the .jnlp program but returns with the message, that the app-desc|applet-desc|installer-desc|component-desc is missing. But it is there: It is an applet and thus I defined an applet-dec.
    I tried to do it from a command line with the followinf command:
    java -Djnlpx.home="C:\abc" -cp "C:\abc\javaws.jar" com.sun.javaws.Main http://a.b/c.jnlp
    And that works. But using this command from within my jjava prog using the Runtime.exec() method does not work.
    By the way, simply type "javaws http://a.b/c.jnlp" at the command line does not work.
    Can anybody help me? How may I start a .jnlp program within another java program.
    Kind Regards,
    Tobias Neubert

    Hi,
    I recently had a quite similar problem. At least the error message by the Java Web Start application on Mac OS X complained about the same error (app-desc|applet-desc|installer-desc|component-desc). It turned out to be some bad invisible characters in the jnlp file. I copied some sample from a web page which for some reason contained some unicode chars that the parser doesn't like. Use a different text editor or the less command on unix to see if there are some strange characters in you jnlp file.
    But it seems strange that it does work from the command line and not from your code.
    -Stefan

  • How to list all OS processes from a java program

    I want to list/kill all OS processes from a java program, or a part from all processes according to a filter on a name of process.
    a similar functionality is ps in Unix or taskkill in Windows XP.
    Thanks!

    Hi,
    I was looking for such lib, but finally I decided to accomplish the job with my fingers end ;-). It maigh be helful for u guys:
    // is written for x based OSs
    private static void killProcess(Process process) {
    if (process == null)
    return;
    process.destroy();
    private static void closeProcessStreams(Process process) {
    try {
    process.getErrorStream().close();
    } catch (IOException eyeOhEx) {
    private static void listPHPs() {
    Process proc = null;
    Runtime rt = Runtime.getRuntime();
    int exitVal = 0;
    try {     
    proc = rt.exec(" ps -C php"); // here use ur filter. issue "man ps" in linux for more info
    catch (Exception ex) {
    System.out.println(ex.getMessage());
    killProcess(proc);
    return;
    try {
    // process the return list of ur command
    InputStream stdReturnStr = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(stdReturnStr);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    String returnMsg = "";
    boolean firstLine = true;
    int[] allPIDs = new int[100]; // finally we have an array of PIDs
    int PIDCount = 0;
    while ( (line = br.readLine()) != null) {
    if (!firstLine){ // the first line is title, ignore it
    returnMsg += line + "\n";
    String PID = line.trim().split(" ")[0];
    System.out.println(PID);
    try{
    allPIDs[PIDCount] = Integer.parseInt(PID);
    PIDCount++;
    }catch(Exception ex){           
    else
    firstLine = false;
    System.out.println(returnMsg);
    catch (Exception t) {
    System.out.println(t.getMessage());
    killProcess(proc);
    return;
    try {
    exitVal = proc.waitFor();
    catch (Exception t) {
    System.out.println(t.getMessage());
    killProcess(proc);
    return;
    closeProcessStreams(proc);
    Thats it!

  • Running executable jar from within a java program

    Is there a way to launch an executable jar in a java program? I tried wrapping the jar in an exe and calling it using Runtime exec() and though this approach works it does only for windows. I want it to work for unix/linux too.

    jaki wrote:
    Yes, but it's a sub process.Nope.
    Hence the calling process doesn't quit unless the called one returns.Wrong.
    My calling program is actually a jar and what Im trying to do is delete the jar after it's done running. But the above method (of launching a separate jar doing the deletion) doesn't seem to work for the above mentioned reason.Wrong.
    If you could tell me any other way it would really be a big help.You don't need any other way. Maybe you need to allow some time for the calling program to wind up. 20 seconds may be overkill, but I'm not in the mood to find how short it can be and still succeed.
    The two classes are packaged in separate jars.import java.io.IOException;
    public class Deletee {
        public static void main(String[] args) {
          try {
             String[] cmds = {"java", "-jar", "E:/temp/Deleter.jar"};
             Runtime.getRuntime().exec(cmds);
             System.exit(0);
          } catch (IOException ex) {
             ex.printStackTrace();
    import java.io.File;
    import javax.swing.JOptionPane;
    public class Deleter {
       public static void main(String[] args) {
          File file = new File("E:/temp/Deletee.jar");
          try {
             Thread.sleep(20000);
          } catch (InterruptedException ex) {
             ex.printStackTrace();
          if (file.delete()) {
             JOptionPane.showMessageDialog(null, "Deleted");
          } else {
             JOptionPane.showMessageDialog(null, "Oops");
    }Try it and see for yourself.
    db

  • Specify a exe running from certain directory from java program

    Hi there,
    I had a java program, which will spawn some child process to run vb COM;
    what I wanted to do: have a child process start the COM from a specific diretory?
    IS there any way to do it from Java, like shell programming?
    Thanks

    I do all my portable shell stuff now in ant.. http://jakarta.apache.org/ant/
    it is an XML driven java script for doing builds.. but it can be used for shell scripting.
    They are also some java scripting languages like jPython but i am not very familiar with them.
    u can also get Cygwin and write unix shell scripts. www.cygwin.com
    hope this helps

  • Displaying a shell from within a Java program

    Hi,
    For some long and twisted reason, I need to execute native programs from a Java program. Since this program is only every intended to be run on Linux, this doesn't bother me breaking the x-platform rules for Java! So, Runtime.exec() is the normal way to do this.
    However, Runtime.exec() runs executes the command and then dishes basck the output once it's finished. The external program I wish to run takes a while and actually prints various pieces of feedback during its processing. I'd like to display this feedback to the user as it happens, rather than dumping it all at the end.
    I can't think of anyway to do this. I've been looking for "Java shells" but they are reimplemented shells with only let you run classes on the classpath. Any ideas from the gurus around here?
    Cheers

    import java.util.*;
    import java.io.*;
    class StreamGobbler extends Thread
    InputStream is;
    String type;
    StreamGobbler(InputStream is, String type)
    this.is = is;
    this.type = type;
    public void run()
    try
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line=null;
    while ( (line = br.readLine()) != null)
    System.out.println(type + "> " + line);
    } catch (IOException ioe)
    ioe.printStackTrace();
    public class GoodLinuxExec
    public static void main(String args[])
    if (args.length < 1)
    System.out.println("USAGE: java GoodLinuxExec <cmd>");
    System.exit(1);
    try
    Runtime rt = Runtime.getRuntime();
    System.out.println("Execing " + args[0]);
    Process proc = rt.exec(args);
    // any error message?
    StreamGobbler errorGobbler = new
    StreamGobbler(proc.getErrorStream(), "ERROR");
    // any output?
    StreamGobbler outputGobbler = new
    StreamGobbler(proc.getInputStream(), "OUTPUT");
    // kick them off
    errorGobbler.start();
    outputGobbler.start();
    // any error???
    int exitVal = proc.waitFor();
    System.out.println("ExitValue: " + exitVal);
    } catch (Throwable t)
    t.printStackTrace();
    stolen from this article and adapted to suit an os which does not start with the letter W.

  • Running Batch file thru a java program

    hai friends
    i have a batch file like hello.bat
    how can i run that batch file when i run my java program
    i heard that Runtime.exec() is used to run the batch files.
    can i use Runtime.exec() to run my hello.bat file or any other things i need to use ?
    Thankyou VeryMuch
    Yours
    Rajesh

    Yes, you can use Runtime. You should look it up in your API guide, but this code might get your started:
            try
                Process p = runtime.exec("command.com /c c:\\hello.bat");
            catch(IOException e)
                System.out.println("Failed");
            }Your API guide will explain how to get a Runtime object. The syntax is very straightforward.

  • How to start a browser from within a java program?

    I want to make a help file for my java program and want to run the browser from the menu of my program.
    How can I start my browser from my program?
    A small code will be helpful.
    Thanks.
    Niteen

    This should work on Windows without having to know where the browser is located. See http://www.javaworld.com/javaworld/javatips/jw-javatip66.html for more details
      public static void viewHtml(URL url, boolean fixHtmlExtension){
          String cmd = "rundll32 url.dll,FileProtocolHandler " + url.toExternalForm();
          if (fixHtmlExtension){
            //There is a bug in rundll32. For http requests, it doesn't like .html or .htm extensions,
            //but replacing the 'm' with '%6D' works. 
            //This fix is not needed for file requests.
            if (cmd.endsWith(".htm")){
              cmd = cmd.substring(0,cmd.length()-1) + "%6D";
            else if (cmd.endsWith(".html")){
              cmd = cmd.substring(0,cmd.length()-2) + "%6Dl";
          Process process = Runtime.getRuntime().exec(cmd);
          try{
            process.waitFor();
          catch(InterruptedException e){

  • URGENT:- Running a batch file from java program

    Author: pkanury
    I am trying to execute a batch file from my java program using RunTime and Process . It can execute any dos command except for a batch file. Can anyone throw
    some light ?? My code looks like this .....
    cmd = "command.com /c X:\\grits\\scripts\\test.bat"; Runtime rt = Runtime.getRuntime(); Process p = rt.exec(cmd);
    The weird part is that p.waitFor() returns a status of 0 implying that the cmd has been executed successfully. But that is not the case. And my batch file is as simple as - type "ADADA" > junk.txt
    Any help would be appreciated.

    I think it should work when you use a String[] array
    instead of a single String:
    String[] cmd = { "command.com", "/C", "D:\\batch\\do.bat" };
    Note: If the batchfile creates any output (i.e. files),
    they will be stored in the directory of the application
    which calls the batch file, not in d:\batch\...

  • Run dial-up connection from Java Program?

    Is there a way to run dial-up connection from a Java Program? It needs to platform independent.
    Thanks.
    Virum

    I very much doubt it, at least not platform independent. I had a, oops, heck of a time doing that from Visual Basic, where it is much easier to work with operating-system stuff like that than it is in Java. I finally ended up buying a RAS component to call from my VB program.

  • Run Perl script in my Java program

    Some say that the following statement can run Perl script in Java program:
    Runtime.getRuntime().exec("C:\\runPerl.pl");
    But when I run it, it'll throw IOException:
    java.io.IOException: CreateProcess: C:\runPerl.pl error=193
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Win32Process.java:63)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:566)
    at java.lang.Runtime.exec(Runtime.java:428)
    at java.lang.Runtime.exec(Runtime.java:364)
    at java.lang.Runtime.exec(Runtime.java:326)
    at test.runPerl.main(runPerl.java:16)
    Exception in thread "main"
    Where is the problem? In fact, I do have a Perl script named "runPerl.pl" in my C:/ directory. Why can't it be run?

    Please don't crosspost
    http://forum.java.sun.com/thread.jspa?threadID=703918

Maybe you are looking for

  • Creation of a portal page using XML web form

    Hi Experts, I want to know how to make a portal page using XML web forms... Please tell me the steps involved in doing the aforesaid. Thanks in advance...

  • Group message not working

    I am not receiving group messages from others, but I cannot send more than 1 message at a time. Ive added them into a group but it only sends to the person first on the recipients.  They do have iphones and samsung galaxys. I have tried to download a

  • MacBook Various Problems

    Hi, I have a Mid-2007 MacBook that is having some problems. - Cracking plastic on front palmrest - Worn trackpad - Non-functioning Optical drive It runs OSX 10.6.8 and it's on its last legs. I would like to sell it back to Apple and put that money to

  • Change tracking file

    Hello, When I enable block change tracking, is it any method to maintain this file? Do we delete and recreate it in any way? Or we just let it stay and grow automatically? Thx for help, Aliq

  • Java 7 Update 67 in App-V 5SP2

    Hi, I am new to the group and app-v product.  Have been assigned to sequence latest version of java 7u67.  will be using win 7 x64 as the sequencer for this task.  What, I would like to achieve is 1. Sequence java 7u67 2. Use the package and deploy t