• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

running a batch file from java

 
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
recently i've tried running a dos batch file from a java program with the following code
String[] cmd = new String[2];
cmd[0] = "cmd.exe";
cmd[1] = "c:\\development\\test.cmd";
//cmd[2] = args[0];
String s = null;

Runtime rt = Runtime.getRuntime();
//System.out.println("executing :" + cmd[0] + " " + cmd[1] + cmd[2]);
Process proc = rt.exec(cmd);
at th last line where i do rt.exec it is giving an array index out of bound exception. can anybody tell me am i doing in the right way or iam missing something else
thanks in advance
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Runtime.getRuntime().exec("cmd /K start whatever.bat");
Look up the cmd.exe instructions in the Windows help section.
 
seetarama raju
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks. i had this working now. but i have another
question. could you please let me know, how to handle a timeout while calling the waitfor method
on the process object. i don't want the process to go on without any response. could you suggest me an easy way to handle timeout so that my program won;t be blocked for this result
thanks
 
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Try calling exec() from a Thread and use join(TIMEOUT_IN_MILLIS).
 
Tony Yan
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
seetarama:
Try this link:
kill a process
You may have similar problem I have had.
Tony
 
seetarama raju
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks. anyway,my another question is , i was a bit cofused when it goes to error stream, and when it goes to inputstream. sometimes even when the exitvalue is zero, it is going to error stream
but not input stream. do you know the reason for this. recently when i gave javac with verbose switch to the runtime.exec(), it had compiled the file i've given and gave exitvalue 0. but all the messages that comes with javac -verbose, went to error stream. i was expecting to get a success condition to input stream. could you tell me the reason for this.
thanks
 
Tony Yan
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Not sure. Supposedly, the subprocess created by Runtime should redirect correctly the IO's to the Java Process that calls the Runtime.exec().
java.lang.Process API:
" The Runtime.exec methods may not work well for special processes on certain native platforms, such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows, or shell scripts. The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (Process.getOutputStream(), Process.getInputStream(), Process.getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. 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. "
Can you provide your code and other info. such as OS and native cmd env?
 
seetarama raju
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
the following is my code, which is giving exitvalue 0, but still goes to error stream
----

import java.io.*;
import java.util.*;
import java.lang.*;

public class runtimeTest {

StringBuffer stdErrorMsg = new StringBuffer();

public static void main(String args[]) {

String[] cmds = new String[3];

try {

cmds[0] = "javac";
cmds[1] = "-verbose";
cmds[2] = "c:\\development\\test.java";



Process proc = Runtime.getRuntime().exec(cmds);


// read any errors from the attempted command
processError(proc.getErrorStream());

// read the standard output from the command
processOutput(proc.getInputStream());
int maxTrials = 5;
int trial = 0;
boolean finished = false;
do {
trial++;
try {
int exitVal = proc.exitValue();
System.out.println("ExitValue is:"+ exitVal);
finished = true;
}
catch(IllegalThreadStateException e) {
finished = false;
}
if(!finished) {
try {
Thread.sleep(10*10000); } catch(InterruptedException e) {};
}
} while( (!finished)|| (trial < maxTrials));

if(!finished) {
throw new IOException();
}

}
catch (IOException e) {
}
catch (Exception e) {
}



System.exit(0);

}// copy files



private static String getNextToken (StringTokenizer izer) {
if (izer.hasMoreTokens())
return izer.nextToken();
else
return null;
}


//tp process the inputStream from the process
private static void processOutput(InputStream is) throws IOException {

InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;

while ((line = br.readLine()) != null) {
System.out.println("entered input process ---");
System.out.println(line);
}//while



}

private static void processError(InputStream is) throws IOException {

InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while( (line = br.readLine()) != null) {
System.out.println("entered the error condition --- ");
System.out.println(line);
}


}



}
 
seetarama raju
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i aslo have another question regarding the exceptions thrown by runtime.exec() method. what i found out was that as long as he command string is given properly and exit value is handled correctly, it is atleast not blocking. it is giving some output. but if there is anything wrong in the command string passed to the runtime.exec() method, then it is just blocking forever. is there anyway i can force the exec() method to throw an exception if it didn't
understand the command string passed. please somebody help me with this, as i got stuck exactly at this point now. because first i want to test whether the command string iam passing is right or not
thanks in advane
 
Tony Yan
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
seetarama:
For the ErrorStream problem, I tried on my pc. It appears to me that's command related. When you use javac -verbose test.java, the command will always set output to stderr regardless. I think javac is designed that way but when you run it in Window's console you don't realize it because both the stdout and stderr go to the console.
I used the following:
cmds[0] = "help";
cmds[1] = "time";
cmds[2] = "-dummyFlag";
in the code and got the following to the OutputStream.

entered input process ---
Displays or sets the system time.
entered input process ---
entered input process ---
TIME [/T | time]
entered input process ---
entered input process ---
Type TIME with no parameters to display the current time setting and a prompt
entered input process ---
for a new one. Press ENTER to keep the same time.
entered input process ---
entered input process ---
If Command Extensions are enabled the TIME command supports
entered input process ---
the /T switch which tells the command to just output the
entered input process ---
current time, without prompting for a new time.
ExitValue is:0
ExitValue is:0
ExitValue is:0
press any key to exit...
So I guess it makes senses now.
For your second question, I tried and when the command is not runnable by the OS (say using 'dir *.*') , it will just exit without any message. And especially for batch commands, it is likely the IO will get blocked and you are at the mercy of the OS handling the stdio's. I am not sure you can solve this problem for all OS'. But the link in previous email about monitoring Threads should be a get around solution. At least, it worked nicely with my Ant build execution. I often have deadlock once out of 100-120 external command, but I will destroy that thread and retry.
Regards,
 
seetarama raju
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks. i will keep trying
 
seetarama raju
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i need to ask you one more small question.
right now iam required to run a shell script from
a java program. the following is a sample piece of code iam using
cmds[0] = "/opt/ssh/bin/scp";
cmds[1] = "-a";
cmds[2] = "/"+sourcedir+"/"+filename;
cmds[3] = username+"@"+targetServer+":/"+destinationdir;

in the above code scp is a shell script in opt/ssh/bin, and -a is a switch. rest are the parameters which are taken from external input.
iam yet to test this on a unix system, which right
now iam not in a position to do. before that i just want you to suggest me any changes in the above piece of code.
thanks for all the help once again
 
Tony Yan
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have no comments about the UNIX command, because I don't know what it does anyway. But as long as you can run it in the shell, it should run from a Java call.
However, you seem to be watching and waiting for a process to run by checking its exit value. I recommend to use Process.waitFor() so you don't have to sleep() for 10*10000 millis, which is an arbitrary interval anyways. I believe the waitFor will wait till the process of command returns an zero exit value.
Another problem you might have is still the deadlock, which has puzzled me for the last 3-4 days. I recommend you put the code in a class YourClass implements Runnable and call from new Thread(new YourClass()).start(). Of course, you have to implement the run() method of YourClass. In the caller, say ThTest class, make sure you do something like join(5000) and which means if a Thread waits more than 5 sec (5000 ms), it is in a deadlock and quit. If the Process is finished before 5 sec, the Thread has died normally, which means the command runs okay.
Hope this all helps.
Regards,
 
seetarama raju
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks for the help. i will get back to you if needed.
 
seetarama raju
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
when iam testing to run the unix shell script,
i was mentioning before, it was working fine. it gave exitvalue 0. but the thing it is writing
into either error stream or inputstream. i was just wondering how to handle an error condition.
actually i was planning to take a token from the
string returned in one of the streams, to handle
a string called 100% for checking the successful or unsuccessful condition. what do you say about this. please let me know if you have any insight
thanks
 
seetarama raju
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
iam sorry. actually in the previous mail i mean to say it was not writing into any of the streams.
share with me if u have any idea.
or is it ok, if i always rely on exitvalue only
for a success condition, instead of looking for an
inputstream.
 
seetarama raju
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Could you please hava a look at my above two mails and let me know about something. i think if i could find something for this, my application will be all set.Meanwhile iam trying diff ways fo this. i will let you know if i find any solution.
thanks in advance
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic