Monitoring a Process using Runtime.exce()

Hi,
In my Program, I'm using the
new BufferedReader(new InputStreamReader(Runtime.getRuntime()                         .exec("ps -ef | grep xmlfeed").getInputStream()));
The above statement is not returning any inputstream to the BuffredReader.
When I gave the command as "PWD", it's returning the lines as expected.
But it's not working even for "PS" command also.I'm running this in AIX machine.
Any Ideas,Please help....
Edited by: haijdp on Dec 21, 2007 1:11 AM

Hello! And sorry I didn't reply earlier. I hope the Original Poster will find revisit this thread and it helps him.
From your post I assumed that you were not a student trying to create some homework. That's why I felt free to simply code a solution and submit the code here. But first some remarks:
I don't think that your code can work. Runtime.exec expects an array of type String, where the first element is the command and subsequent elements are a command line option each. I don't think you can use the pipe and call several commands using Runtime.exec, but that's just a kind of guess. YMMV.
Running external Processes in Java is a bit complicated. Basically,
* It's good to run the process in it's own thread. That way the main program can continue without getting stuck.
* To extract stdout and stderr of your target process you must run two threads, one for stderr and one for stdout. Both threads extract the characters of their respective streams in a loop that runs inside the thread. Again, that way we avoid deadlocks, program getting stuck etc.
This explanation is terrible, I know - I think a slice of source code speaks louder than words. I have attached five java files which together make a little process runner which extracts stdout and stderr in a safe manner. To run:
* Cut'n paste them into five text files, one per class.
* Save the each text file as {contained-class-name}.java
* Compile the stuff
* Run RunnerDemo (When I ran it, I got a directory listing printed on the console)
Explanation sounds a bit sloppy, but I did it under the assumption that you are a seasoned java pro, so it should not pose any problems. Since you seem to be a different OS than I (AIX, I run Linux), the command may or may not work. Try other commands. For example, in the RunnerDemo class you could set the cmd field to this:
        String [] cmd =
            "ps",
            "-A",
            "-H"
        };This would give you a process listing (works on Linux).
By the way, commands are passed as array. See Java documentation for java.lang.Runtime.exec (String []) for explanation of this array.
One problem I see in your command is that the output of ps is piped to some other program. Sorry, I don't know whether my code could achieve this. All it can do is to rum one single command with command line options. But you should be able to adjust the given example, so it supports piping to another program.
If you have any further questions, please don't hesitate to ask!
Class: RunnerDemo
*                           RunnerDemo.java
*                     Demo for the process runner
package rtimeexec;
public class RunnerDemo
    public static void main (String [] args)
        String [] cmd =
            "ls",
            "-a",
            "-l"
        ProcessRunner   runner;
        String          stdOutStr;
        String          stdErrStr;
        runner = new ProcessRunner (cmd);
        runner.start ();
        runner.BlockUntilFinished ();
        stdOutStr = runner.GetStdOutText ();
        stdErrStr = runner.GetStdErrText ();
        System.out.println ("Process result, ls -a -l");
        System.out.println ("-----------------------------------------------------------------------");
        System.out.println ("Stdout:");
        System.out.println ("-----------------------------------------------------------------------");
        System.out.println (stdOutStr);
        System.out.println ();
        System.out.println ("-----------------------------------------------------------------------");
        System.out.println ("Stderr:");
        System.out.println ("-----------------------------------------------------------------------");
        System.out.println (stdErrStr);
Class: ProcessRunner
package rtimeexec;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
* Runs a system process and extracts stdout and stderr of that process.
* Process will run in its own thread, so that the caller can simply continue
* with less of a chance to get locked down. Caller can invoke the {@link BlockUntilFinished}
* method after starting this thread. This method blocks until the thread is finished,
* i.e. the process has finished.
* Unfortunately, we haven't implemented any facility to stream characters to
* stdin of the process called. If that facility would exist we could refactor
* the classes and realize some sort of piping facility, as it's possible in
* Linux, for example.
* Example on how to run a process:
* <pre>
* String []         cmd  = {"ps", "-AH"};
* String            sOut;
* String            sErr;
* ProcessRunner     runner;
* runner = new ProcessRunner (cmd);
* runner.start ();
* runner.BlockUntilFinished ();
* sOut = runner.GetStdOutText ();
* sErr = runner.GetStdErrText ();
* System.out.println ("Stdout:");
* System.out.println (sOut);
* System.out.println ("------------------------------------------------------");
* System.out.println ("Stderr:");
* System.out.println (sErr);
* </pre>
public class ProcessRunner extends Thread
    private String []                   command;
    private int                         execResult;
    private String                      stdOutText;
    private String                      stdErrText;
    private boolean                     isFinished;
    public ProcessRunner (String [] cmd)
        command     = cmd;
        execResult  = 0;
        stdOutText  = null;
        stdErrText  = null;
        isFinished  = false;
    public int GetResult ()
        return execResult;
    public String GetStdOutText ()
        return stdOutText;
    public String GetStdErrText ()
        return stdErrText;
    public boolean IsFinished ()
        return isFinished;
    public void BlockUntilFinished ()
        while (! isFinished)
            try {Thread.sleep (250);} catch (InterruptedException e) {}
    public void run ()
        Process         proc;
        Runtime         rt;
        InputStream     stdOut;
        InputStream     stdErr;
        CharStream      stdOutEx;
        CharStream      stdErrEx;
        int             res;
        isFinished = false;
        try
            res         = 0;
            rt          = Runtime.getRuntime ;       ();
            proc        = rt.exec ;                  (command);
            stdOut      = proc.getInputStream ;      ();
            stdErr      = proc.getErrorStream ;      ();
            stdOutEx    = new CharStream            (stdOut);
            stdErrEx    = new CharStream            (stdErr);
            stdOutEx.start ();
            stdErrEx.start ();
            try {res = proc.waitFor ();} catch (InterruptedException e) {}
            // Process has finished; now wait until any buffers are empty.
            stdOutEx.BlockUntilFinished ();
            stdErrEx.BlockUntilFinished ();
            stdOutText = stdOutEx.GetResult ();
            stdErrText = stdErrEx.GetResult ();
            execResult = res;
        catch (IOException e)
            isFinished = true;
            throw new ExtractionException (e.getLocalizedMessage());
        isFinished = true;
Class: CharStream
package rtimeexec;
import java.io.IOException;
import java.io.InputStream;
* A Character extractor. Extracts characters from a stream and puts them
* into a String. To protect from memory overflow we put a limit in place.
* When storage demads exceed that limit, an exception is thrown.
public class CharStream extends Thread
    private static final int    maxChunkLen         = 8192;
    private static final int    maxStorageSize      = 512 * 1024;   // 512 KBytes
    private InputStream     sourceStream;
    private StringBuffer    extracted;
    private boolean         isFinished;
    public CharStream (InputStream istream)
        sourceStream    = istream;
        extracted       = new StringBuffer ();
        isFinished      = false;
    public String GetResult ()
        String ret;
        ret = extracted.toString ();
        return ret;
    public void BlockUntilFinished ()
        while (! isFinished)
            SleepThread (250);
    public void run ()
        byte []                 buffer;
        int                     nBytesRead;
        byte                    b;
        char                    c;
        int                     iChar;
        int                     nCharsTotal;
        boolean                 isEOF;
        isEOF       = false;
        nCharsTotal = 0;
        isFinished = false;
        while (! isEOF)
            try
                buffer      = new byte [maxChunkLen];
                nBytesRead  = sourceStream.read (buffer);
                if (nBytesRead >= 1)
                {   // much faster stream extraction method than when we use
                    // BufferedReader(new InputStreamReader(sourceStream)).
                    for (iChar = 0; iChar < nBytesRead; iChar++)
                        nCharsTotal++;
                        if (nCharsTotal > maxStorageSize)
                            throw new StoreFullException
                                "Storage limit exceeded (" + Integer.toString (maxChunkLen) + "Bytes)"
                        b = buffer [iChar];
                        c = (char) b;
                        extracted.append (c);
                else if (nBytesRead <= -1)
                    isEOF       = true;
            catch (IOException e)
                isFinished = true;
                throw new ExtractionException (e.getLocalizedMessage());
            SleepThread (250);
        isFinished  = true;
    private void SleepThread (int mSec)
        try
            Thread.sleep (mSec);
        catch (InterruptedException e)
Class: StoreFullException
package rtimeexec;
* Exception that gets thrown when a storage container is full.
public class StoreFullException extends RuntimeException
    private static final long serialVersionUID = - 4996246591135389009L;
    public StoreFullException (String message)
        super (message);
Class: ExtractionException
package rtimeexec;
* Thrown when there was some problem during stream extraction.
public class ExtractionException extends RuntimeException
    private static final long serialVersionUID = - 6124525536783450209L;
    public ExtractionException (String message)
        super (message);
}

Similar Messages

  • Spawn a java process using runtime.exec() method

    Hi,
    This is my first post in this forum. I have a small problem. I am trying to spawn a java process using Runtime.getRuntime().exec() method in Solaris. However, there is no result in this check the follwoing program.
    /* Program Starts here */
    import java.io.*;
    public class Test {
    public static void main(String args[]) {
    String cmd[] = {"java", "-version"};
    Runtime runtime = Runtime.getRuntime();
    try{
    Process proc = runtime.exec(cmd);
    }catch(Exception ioException){
    ioException.printStackTrace();
    /* Program ends here */
    There is neither any exception nor any result.
    The result I am expecting is it should print the following:
    java version "1.4.0"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92)
    Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode)
    Please help me out in this regard
    Thanks in advance
    Chotu.

    Yes your right. It is proc.getInputStream() or proc.getErrorStream(). That is what I get for trying to use my memory instead of looking it up. Though hopefully the OP would have seen the return type of the other methods and figured it out.

  • Issue regarding creating a process using Runtime in Windows 2003.

    Hi all..
    I need to resolve a small issue related to execute an external program using runtime execution method. But when i deploy the code in websphere application server 6.1V in windows 2003 server operating system, it is starting a process with min priority and not executing even i specified waitfor method.
    The code is like below.
    try{
    Process p = Runtime.getRuntime().exec("C:\\CopyImages.exe "+toWrite);
    int ep = p.waitFor();
    System.out.println("process "+ep);
    catch(Exception e)
    e.printStackTrace();
    Please help me in resolving this issue. The above code is working in my IDE which is in Window XP but when i port it in application server in windows2003 i'm getting this issue.

    hi..
    it is a typo error. i've given the slashes with that.
    but still getting the problem.

  • Error in creating a process using runtime class - please help

    Hi,
    I am experimenting with the following piece of code. I tried to run it in one windows machine and it works fine. But i tried to run it in a different windows machine i get error in creating a process. The error is attached below the code. I don't understand why i couldn't create a process with the 'exec' command in the second machine. Can anyone please help?
    CODE:
    import java.io.*;
    class test{
    public static void main(String[] args){
    try{
    Runtime r = Runtime.getRuntime();
         Process p = null;
         p= r.exec("dir");
         BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
         System.out.println(br.readLine());
    catch(Exception e){e.printStackTrace();}
    ERROR (when run in the dos prompt):
    java.io.IOException: CreateProcess: dir error=2
    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:550)
    at java.lang.Runtime.exec(Runtime.java:416)
    at java.lang.Runtime.exec(Runtime.java:358)
    at java.lang.Runtime.exec(Runtime.java:322)
    at test.main(test.java:16)
    thanks,
    Divya

    As much as I understand from the readings in the forums, Runtime.exec can only run commands that are in files, not native commands.
    Hmm how do I explain that again?
    Here:
    Assuming a command is an executable program
    Under the Windows operating system, many new programmers stumble upon Runtime.exec() when trying to use it for nonexecutable commands like dir and copy. Subsequently, they run into Runtime.exec()'s third pitfall. Listing 4.4 demonstrates exactly that:
    Listing 4.4 BadExecWinDir.java
    import java.util.*;
    import java.io.*;
    public class BadExecWinDir
    public static void main(String args[])
    try
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("dir");
    InputStream stdin = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(stdin);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    System.out.println("<OUTPUT>");
    while ( (line = br.readLine()) != null)
    System.out.println(line);
    System.out.println("</OUTPUT>");
    int exitVal = proc.waitFor();
    System.out.println("Process exitValue: " + exitVal);
    } catch (Throwable t)
    t.printStackTrace();
    A run of BadExecWinDir produces:
    E:\classes\com\javaworld\jpitfalls\article2>java BadExecWinDir
    java.io.IOException: CreateProcess: dir error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Unknown Source)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at BadExecWinDir.main(BadExecWinDir.java:12)
    As stated earlier, the error value of 2 means "file not found," which, in this case, means that the executable named dir.exe could not be found. That's because the directory command is part of the Windows command interpreter and not a separate executable. To run the Windows command interpreter, execute either command.com or cmd.exe, depending on the Windows operating system you use. Listing 4.5 runs a copy of the Windows command interpreter and then executes the user-supplied command (e.g., dir).
    Taken from:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Monitor ETL process using SNMP

    Hi,
    I have an ETL process that runs continuously and add lines to a table under Oracle 11g on Linux. I would like to monitor the proper operation of the ETL using an external SNMP manager (eg Zabbix). To do this the algorithm would be like this:
    - List and count lines that have been to the table durig the last n minutes;
    - Update an SNMP counter
    - Repeat every n minutes.
    I was thinking about creating a small Perl subagent for net-snmp that would execute an SQL query using JDBC, but is there a better way to do this? For instance by using an Ora

    I assume you're talking about scripting this? Probably the easiest thing to do would be to use Curl. I've attached an example. You'll need to change a couple values for it to work.
    The output is different than what you'd get if you did a "df" using the service account. You'll have to decide which output you require.

  • Ping application using runtime.exce(pingComand)

    Hi,
    I am writing an application that is going to automate the ping command. I am not using the isReachable() because the server that i will be testing my machines have the firewall - and i have tested the code works and does what it is supposed to do.
    I am using the:
    Runtime r = Runtime.getRuntime();
    Process p = r.exec(pingCmd);
    where i am pinging, and getting the result from the dos:
    InputStreamReader(p.getInputStream()));
    and then changing the gui appropriattly (red == dead, green ==alive). The code is working, but the gui does not get updated until the last process (ping) has been executed. As i am pinging about 20 machines, it is taking a long time for the gui to be updated.
    I want to update the gui after[u] (or maybe during the ping as well ==yellow) each i get the result of the r.exec(pingCmd);, is there a way to make any threads sleep or, i am stuck.
    Regards,
    Amir

    This is the method that i am using to do a ping, and then read the text returned (as would be seen on does when you do a 'ping ipAddress').
    public String doPingCMD(String sIP) {
              String ip = sIP;
              String pingResult = "";
              String pingCmd = "ping " + ip;
              try {
                        Runtime r = Runtime.getRuntime();
                        Process p = r.exec(pingCmd);
                        BufferedReader in = new BufferedReader(new
                        InputStreamReader(p.getInputStream()));
                        String inputLine;
                        while ((inputLine = in.readLine()) != null) {
                                  pingResult += inputLine;
                        in.close();
              catch (IOException e) {
                        System.out.println(e);
              return pingResult;
    This is doing a ping and returning the accurate text but it only does this one at a time. So imagin when i am having to do the same thing (one after another for 20 maichines (20 ip addresses) - it is taking very long - and the gui does not get updated untile the very last ping executes.

  • Start a new java process using Runtime.Exec() seems to ignore the -Xmx

    I am working with a process that requires a minimum of 1.5 GB to run and works better if more is available.
    So I am determining how much memory is available at startup and restarting the jre by calling
    Runtime.exec("java -Dcom.sun.management.jmxremote=true -Xmx1500M -jar XXX.jar")
    which reinvokes the same process with a new max memory size.
    The initial call to the process is
    java -Dcom.sun.management.jmxremote=true -Xmx3500M -jar XXX.jar
    The initial call returns 3262251008 from Runtime.maxmemory()
    When reinvoked through Runtime.exec() as above
    Runtime.maxmemory() still returns 3262251008
    Is there a way to separate the new process from the size specified by the parent process?

    That is strange. Here is a program I wrote which calls itself recursively.
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    import java.util.ArrayList;
    import static java.util.Arrays.asList;
    public class MemorySize {
        public static void main(String... args) throws IOException, InterruptedException {
            System.out.println("Maximum memory size= "+Runtime.getRuntime().maxMemory());
            if (args.length == 0) return;
            List<String> cmd = new ArrayList<String>();
            cmd.add("java");
            cmd.add("-cp");
            cmd.add(System.getProperty("java.class.path"));
            cmd.add("-Xmx"+args[0]+'m');
            cmd.add("MemorySize");
            cmd.addAll(asList(args).subList(1,args.length));
            Process p = new ProcessBuilder(cmd).start();
            readin(p.getErrorStream());
            readin(p.getInputStream());
        private static void readin(final InputStream in) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        byte[] bytes = new byte[1024];
                        int len;
                        while((len = in.read(bytes))>0)
                            System.out.write(bytes, 0, len);
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
            }).start();
    }If you run this with the args 128 96 33 222 it prints out
    Maximum memory size= 66650112
    Maximum memory size= 133234688
    Maximum memory size= 99942400
    Maximum memory size= 35389440
    Maximum memory size= 231014400

  • Using runtime.exec,process streams

    Hi all,
    I am using runtime.exec to execute a batch file(rmdir /s/q directoryname) which deletes all the files in a certain directory(including subdirectories). However, some of the files are not deleted since they are being used by other processes.
    I have closed all file references but still the batch file says they are being used by other processes. The File.canWrite() method however, returns true for all the files. I have also tried to delete the files using file.delete but it does not work.
    So I have 2 questions.
    1. Can I forcibly delete these files some other way.
    2. If i call a batch file to delete the files and it fails on some files, the command window displays "cannot delete files". How can I write out thse messages into a text file which i can use as a log file.Do I have to use Process.getInputstream()/Process.getInputstream() ? If so, how?
    Thanks for your help.
    Vinny

    I tried the following before but the string i get is always empty, but i can see there are messages in the command window. Please let me now if i am doing something wrong.
    try{
    Process p = rt.exec("cmd.exe /c start deletefiles.bat");
    InputStream ins = p.getInputStream();
    byte[] bytearray = new byte[1024];
    int bytecount;
    String dos_string="";
    BufferedInputStream bis = new BufferedInputStream(ins);
    while ((bytecount = bis.read(bytearray, 0, 1024)) > -1) {
    String str = new String(bytearray,0,bytecount);
    dos_string += str;
    System.out.println("dos string is" +dos_string);
    catch (Exception e) {
    System.out.println("Error: " + e);

  • How BAM can use to monitor B2B process?

    We have a BPEL process that is using B2B piece for connecting Trading partner and want to monitor whole process from Start of the BPEL to end of the B2B.
    Here are the questions.
    Q1. We know by using BAM sensor on BPEL process we can monitor the BPEL prcocess but how about B2B piece?
    Q2. What are the best practices for capturing and reading transactional data in various phases and functional acknowledgement messages from a B2B server?
    Thanks in advance for your reply.

    Please send a note to [email protected] for a document on BAM-B2B integration.

  • 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

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

  • OWB issue using runtime repository

    For batches to load data into the datawarehouse, we use .bat files.
    Somewhere in the .bat file we call a deployed mapping(.pls a package in the database), normaly it end with a succes status.
    But the last time we have 2 problems;
    - if there is a error while processing mapping the mapping does not stop at the error but continues. This is a big problem! When the error occurs somewhere in the mapping the mapping must stop.
    - normally in the batch one of the many mappings is ready in 1 minute but now it is busy for more then 3 hours and the only thing we can see is in the runtime assistant, there we only see that the mapping is busy but not what the mapping is doing.
    We have created all tables, functions and mappings etc with Oracle Warehouse Builder and deployed all objects.
    Does someone knows what to do?
    regards,
    Marinda

    - if there is a error while processing mapping the
    mapping does not stop at the error but continues.
    This is a big problem! When the error occurs
    somewhere in the mapping the mapping must stop.Set the mapping to have maximum errors allowed = 0 by right-clicking the appropriate mapping -> Configure... -> "Runtime Parameters" -> Maximum Number of Errors = 0. It will quit processing immediatelly.
    - normally in the batch one of the many mappings is
    ready in 1 minute but now it is busy for more then 3
    hours and the only thing we can see is in the runtime
    assistant, there we only see that the mapping is busy
    but not what the mapping is doing.This is a tough one to answer from here. The problem here could reside on your mapping, on Database side, on the hardware/software architecture...
    Do other mappings runs in a feasible time? If so, it might be related only to this mapping so you'll have to find out what is causing performance issues. Try to monitor this procedure using Statspack, discover what are the bottlenecks for this processing.
    Does someone knows what to do?Unfortunatelly I can't answer the second question
    Regards,
    Marcos

  • Socket stays open after java process exits, Runtime.exec()

    I have a program that does the following:
    opens a socket
    Does a runtime.exec() of another program
    then the main program exits.
    what i am seeing is, as long as the exec'd program is running, the socket remains open.
    What can i do to get the socket to close?
    I even tried to explicity call close() on it, and that didn't work. Any ideas would be great.
    I am running this on WindowsXP using netstat to monitor the port utilization.
    here is some sample code
    import java.io.*;
    import java.net.*;
    public class ForkTest
        public static void main(String[] args)
            try
                DatagramSocket s = new DatagramSocket(2006);
                Process p = Runtime.getRuntime().exec("notepad.exe");
                System.out.println("Press any key to exit");
                System.in.read();
            catch (IOException ex)
                ex.printStackTrace();
    }

    java.net.BindException: Address already in use: Cannot bind
            at java.net.PlainDatagramSocketImpl.bind(Native Method)
            at java.net.DatagramSocket.bind(DatagramSocket.java:368)
            at java.net.DatagramSocket.<init>(DatagramSocket.java:210)
            at java.net.DatagramSocket.<init>(DatagramSocket.java:261)
            at java.net.DatagramSocket.<init>(DatagramSocket.java:234)
            at ForkTest.main(ForkTest.java:11)

  • Getting the output from a Perl script using Runtime.exec

    I cannot get the output from a perl script using Java. Can someone PLEASE help?
    I used the following code:
    Process p = Runtime.getRuntime().exec("C:\\Perl\\bin\\Perl.exe script.pl) ;
    InputSream in = p.getInputStream();
    b...
    do
    System.out.println(b);
    while ((b = in.read()) > 0)
    But there is no way that I get the output in the inputstream. If I use the command "cmd script.pl", the output is displayed in the Dos box, but also not in the inputstream.
    I will appreciate any help.

    Try this
    Process p = Runtime.getRuntime().exec("C:\\Perl\\bin\\Perl.exe script.pl) ;
    BufferedReader rd = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String str;
    while((str=rd.readLine())!=null){
    System.out.println(str);
    Manu

  • Executing a command using Runtime Class

    How to execute a command on a differnet machine with different ipaddress using Runtime Class
    My code is
    String[] cmd = new String[3];
    cmd[0] = "192.1...../c:/WINNT/system32/cmd.exe" ;
    cmd[1] = "/C" ;
    cmd[2] = args[0];
    Runtime rt = Runtime.getRuntime();
    System.out.println("Execing " + cmd[0] + " " + cmd[1]
    + " " + cmd[2]);
    Process proc = rt.exec(cmd);
    // any error???
    int exitVal = proc.waitFor();
    System.out.println("ExitValue: " + exitVal);
    This is not Working

    I have same issue. Actually when I use cmd.exe /c set in java code and if I run the java code in DOS propmt, it retrieves all latest user Environment variable values. But if I run the code in windows batch file, it is not retrieveing the latest user environment values until I reboot my computer, Do you know how to get user environment value with out rebooting machine??????

Maybe you are looking for