Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2006

Tip: Looking for answers? Try searching our database.

Runtime.exec() fails sometime to execute a command

Thread view: 
jaideep.barde@gmail.com - 30 Nov 2006 08:46 GMT
Hello,
I have a program thats using Runtime.exec to execute some external
programs sequence with some redirection operators.
For e.g, I have some command as follows;
1 - C:\bin\IBRSD.exe  IBRSD -s
2 - C:\bin\mcstat -n @punduk444:5000#mc  -l c:\ | grep -i running |
grep -v grep |wc -l
3 - ping punduk444 | grep "100%" | wc -l

...etc.
These command in sequence for a single run. The test program makes
multiple such runs. So my problem is sometimes the runtime.exec() fails
to execute some of the commands above (typically the 2nd one). The
waitFor() returns error code (-1). That is if I loop these commands for
say 30 runs then in some 1~4 runs the 2nd command fails to execute and
return -1 error code.

Can some one help me out to as why this is happening? Any help is
appreciated
Thanks,
~jaideep

Herer is the code snippet;

Runtime runtime = Runtime.getRuntime();
//create process object to handle result
Process process = null;
commandToRun = "cmd /c " + command;
process = runtime.exec( commandToRun  );

CommandOutputReader cmdError = new
CommandOutputReader(process.getErrorStream());
CommandOutputReader cmdOutput = new
CommandOutputReader(process.getInputStream());
cmdError.start();
cmdOutput.start();

CheckProcess chkProcess = new CheckProcess(process);
chkProcess.start();

int retValue = process.waitFor();

if(retValue != 0)
{
    return -1;
}
output = cmdOutput.getOutputData();

cmdError = null;
cmdOutput = null;
chkProcess = null;

/*******************************supporting CommandOutputReader  class
*********************************/
public class CommandOutputReader extends Thread
{
    private transient InputStream inputStream; //to get output of any
command
    private transient String    output;            //output will store command output
    protected boolean isDone;

    public CommandOutputReader()
    {
        super();
        output = "";
        this.inputStream = null;
    }

    public CommandOutputReader(InputStream stream)
    {
        super();
        output = "";
        this.inputStream = stream;
    }

    public void setStream(InputStream stream)
    {
        this.inputStream = stream;
    }

    public String getOutputData()
    {
        return     output;
    }

    public void run()
    {
        if(inputStream != null)
        {
            final BufferedReader bufferReader = new BufferedReader(new
InputStreamReader(inputStream), 1024 * 128);
            String line = null;
            try
            {
                while ( (line = bufferReader.readLine()) != null)
                {
                    if (ResourceString.getLocale() != null)
                        Utility.log(Level.DEBUG,line);
                    //output += line +
System.getProperty(Constants.ALL_NEWLINE_GETPROPERTY_PARAM);
                    output += line + "\r\n";
                    System.out.println("<< "+  this.getId() + " >>" + output );
                }

                System.out.println("<< "+  this.getId() + " >>" + "closed the i/p
stream...");
                inputStream.close();
                bufferReader.close();

            }
            catch (IOException objIOException)
            {
                if (ResourceString.getLocale() != null)
                 {
                     Utility.log(Level.ERROR,
ResourceString.getString("io_exeception_reading_cmd_output")+
                         objIOException.getMessage());
                     output =
ResourceString.getString("io_exeception_reading_cmd_output");
                 }
                 else
                 {
                     output = "io exeception reading cmd output";
                 }
            }
            finally {
                 isDone = true;
            }
        }
    }

    public boolean isDone() {
        return isDone;
    }
}

/*******************************supporting CommandOutputReader  class
*********************************/

/*******************************supporting process controller class
*********************************/
public class CheckProcess extends Thread
{
    private transient Process monitoredProcess;
    private transient boolean continueLoop ;
    private transient long maxWait = Constants.WAIT_PERIOD;

    public CheckProcess(Process monitoredProcess)
    {
        super();
        this.monitoredProcess = monitoredProcess;
        continueLoop =true;
    }

    public void setMaxWait(final long max)
    {
        this.maxWait = max;
    }

    public void stopProcess()
    {
        continueLoop=false;
    }

    public void run()
    {
        //long start1 = java.util.Calendar.getInstance().getTimeInMillis();
        final long start1 = System.currentTimeMillis();

        while (true && continueLoop)
        {
            // after maxWait millis, stops monitoredProcess and return
            if (System.currentTimeMillis() - start1 > maxWait)
            {
                if(monitoredProcess != null)
                {
                    monitoredProcess.destroy();
                    //available for garbage collection
                    // @PMD:REVIEWED:NullAssignment: by jbarde on 9/28/06 7:29 PM
                    monitoredProcess = null;
                    return;
                }
            }
            try
            {
                sleep(1000);
            }
            catch (InterruptedException e)
            {
                if (ResourceString.getLocale() != null)
                {
                    Utility.log(Level.ERROR,
ResourceString.getString("exception_in_sleep") +
e.getLocalizedMessage());
                    System.out.println(ResourceString.getString("exception_in_sleep")
+ e.getLocalizedMessage());
                }
                else
                {
                    System.out.println("Exception in sleep" +
e.getLocalizedMessage());
                }
            }
        }

        if(monitoredProcess != null)
        {
            monitoredProcess.destroy();
            //available for garbage collection
            // @PMD:REVIEWED:NullAssignment: by jbarde on 9/28/06 7:29 PM
            monitoredProcess = null;
        }

    }
}
/*******************************supporting  process controller class
*********************************/
Andreas Leitgeb - 30 Nov 2006 17:09 GMT
> I have a program thats using Runtime.exec to execute some external
> programs sequence with some redirection operators.
> For e.g, I have some command as follows;

> 1 - C:\bin\IBRSD.exe  IBRSD -s
> 2 - C:\bin\mcstat -n @punduk444:5000#mc  -l c:\ | grep -i running | grep -v grep |wc -l
> 3 - ping punduk444 | grep "100%" | wc -l

> commandToRun = "cmd /c " + command;
> process = runtime.exec( commandToRun  );

If you read the docu for  Runtime.exec() (the one with
plain String argument first), then you see, what cmd will
get to see, and perhaps it's not what you expected.

Btw., there are tricks with grep to avoid the extra inverse-grepping
for "grep" itself, and the separate line-counting, as well:

... | grep -ci [r]unning

The "-c" does the match-line counting, and the square brackets
around any literal char in the match-word will prevent grep
from seeing it's own argument in the ps-output.

PS: If you're using some unix-toolkit on windows, why not also
     a proper shell?


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.