Executing subprocess using exec method
I want to run an exe file which is made in C and which accepts command line arguments. For this i m first getting runtime instance and then calling exec() method with name of the file to be executed and arguments i.e. command line arguments which it is accepting. But i m not able to run that exe file. I m getting IllegalThreadStateExeception. When i m running an exe file which is not accepting any command line arguments i m able to run that exe file and obtained the o/p also using getInputStream method of Runtime.
Please tell me how to run an exe file made in C which accepts command line args.
Runtime rt= Runtime.getRuntime();
String[] cmd= new String[4];
cmd[0]= "*.exe";
cmd[1]= "arg1";
cmd[2]= "arg2";
cmd[3]= "argn";
String[] env= new String[1];
env[0]= "path" // such as c:\myfolder
Process process= rt.exec(cmd, env, workingDir);
Similar Messages
-
Running batch files from Java using exec method
Hi,
I want to run a batch file from my Java program like this:
try {
Process proc = Runtime.getRuntime().exec("C:\\Refresh.bat");
catch (Exception e) {
MessageBox.show(e.getMessage());
Refresh.bat file contains two commands.
First one unzips certain zip file.
Second one refreshes a SQL Server database using osql utility.
Problem is that when program is run it executes only the first command and hangs on the second one.
Please help.
TIA
RavinderFrom the FAQ:
2. How do you launch an external program on a Microsoft Windows platform from a program developed on the Java [tm] programming language?
The following will launch notepad in Microsoft Windows NT:
Runtime.getRuntime().exec("cmd /c notepad.exe");
To launch a program in Microsoft Windows 95/98 use:
Runtime.getRuntime().exec("c:\\windows\\notepad.exe");
The Runtime class allows interaction between a program and its environment. The first string command instructs the command line interpretor, cmd to open up the calculator application.
The exec() methods do not use a shell; any arguments must have the full pathname to the shell as well as the command itself.
For example, to run a shell on the UNIX� platform, type:
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("/usr/bin/sh -c date");
To run a batch file under Microsoft Windows 95/98:
Process p = rt.exec("command.com /c c:\\mydir\\myfile.bat");
To run a batch file under Microsoft Windows NT:
Process p = rt.exec("cmd /c c:\\mydir\\myfile.bat");
where 'cmd' and 'command.com' are the command-line interpreters for Microsoft Windows machines.
The Runtime.exec() methods might not work effectively for some processes on certain platforms. Special care should be taken with native windowing, daemon, WIN16/DOS process or some shell scripts.
regards,
jarshe -
Null Pointer Exception when using exec() method of runtime.
Hi There,
I am using a Random Access File to access text data. Then I am using the text data with the Runtime class to activate native programs (such as Word, Outlook, etc).
I have designed my code so that the length of the text file is compared to the current file pointer. If the current file pointer is less than the length of the file then a string is loaded with the text (path) details relevant for the activation of a program (e.g.: Word). In the case where the end of text data in the file has been reached I load the relevant string with null. Here is a little run down of the code:
String Path1;
long FileLength = TxtFile.length(); //Find file length.
long PointerPosition = TxtFile.getFilePointer(); //Find current position
try
if(PointerPosition < FileLength)
Path1 = TxtFile.readLine(); //Read line into string
else
Path1 = null; //Make string null.
}catch(IOException e){}Once the code above has been run I then use the Runtime class's exec() method along with path details held in the string to start a native program as follows:
if(e.getActionCommand().equals("Word"))
if(Path1.equals(null))
EntryBox = new DataEntryBox(); //Create a dialog box for user.
else
try
Runtime.getRuntime().exec(new String[]{Path1}); //Starts prog
catch(IOException f){}
}Whenever I press a button on my program that does not contain a path and instead contains the null value for the relevant string I get the following error message:
C:\j2sdk1.4.0\bin\javaw -classpath "D:\Java\JavaQuickLauncher\classes;C:\j2sdk1.4.0\jre\lib\charsets.jar;C:\j2sdk1.4.0\jre\lib\jaws.jar;C:\j2sdk1.4.0\jre\lib\jce.jar;C:\j2sdk1.4.0\jre\lib\jsse.jar;C:\j2sdk1.4.0\jre\lib\rt.jar;C:\j2sdk1.4.0\jre\lib\sunrsasign.jar;C:\j2sdk1.4.0\jre\lib\ext\dnsns.jar;C:\j2sdk1.4.0\jre\lib\ext\ldapsec.jar;C:\j2sdk1.4.0\jre\lib\ext\localedata.jar;C:\j2sdk1.4.0\jre\lib\ext\sunjce_provider.jar;C:\j2sdk1.4.0\lib\dt.jar;C:\j2sdk1.4.0\lib\htmlconverter.jar;C:\j2sdk1.4.0\lib\tools.jar;C:\j2sdk1.4.0\demo\plugin\jfc\Java2D\Java2Demo.jar;C:\j2sdk1.4.0\demo\jfc\Java2D\Java2Demo.jar" javaquicklauncher.Begin
java.lang.NullPointerException
at javaquicklauncher.GUI.actionPerformed(GUI.java:160)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1767)
at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1820)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:419)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:258)
at java.awt.Component.processMouseEvent(Component.java:5021)
at java.awt.Component.processEvent(Component.java:4818)
at java.awt.Container.processEvent(Container.java:1380)
at java.awt.Component.dispatchEventImpl(Component.java:3526)
at java.awt.Container.dispatchEventImpl(Container.java:1437)
at java.awt.Component.dispatchEvent(Component.java:3367)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3214)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:2929)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2859)
at java.awt.Container.dispatchEventImpl(Container.java:1423)
at java.awt.Window.dispatchEventImpl(Window.java:1566)
at java.awt.Component.dispatchEvent(Component.java:3367)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:445)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:190)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:144)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)
It is my feeling that the exec() method of Runtime is causing this ream of errors, however I feel that my test condition -- if(Path1.equals(null)) -- should avoid trying to run the exec() method when the string is truly null. I am really stuck with this one, any help / suggestions will be greatly appreciated.
Thanks for your time.Path.equals(null) ... and if the Path is null u ll get a NullPointerException.
U r trying to do an equals on null. -
How to Use Exec function in Java Code
How to Use Exec method
I want to Execute command
net Start "some service"
using exec method of runtime class
or i use some other way if suggestAssuming you have read http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#exec(java.lang.String) already, I can only suggest to be more specific in what your problems are. If you are after just some example code, then download ftp://ftp.ebi.ac.uk/pub/software/textmining/monq/monq.tar.gz and have a look at the source code of monq.stuff.Exec. It does all those things which are necessary to keep track of a Process after it was created with exec.
Harald.
BioMed Information Extraction: http://www.ebi.ac.uk/Rebholz-srv/whatizit -
Doubt on exec method from Process class
i want to use exec method from Process class to run an external exe.
now the problem is that Process is an abstract class and hence cant be instantiated.nor can i access exec method directly even though i import the required packages as its not static.how can i go about using exec() if thats the case.
Also can i run a file like notepad.exe present in system32 by providing the path of notepad.exe as an arguement in execi would be really grateful to you if you can write
the syntax for me along eith the class.i tried it out
and i got a lot of errors
this is what i obbtained from the documentation
"public Process exec(String command)
throws IOException"
l to comprehend is what that class Process is doing
in the syntax.from the method its supposed to return
Process class.can you explain it and the usage of
exec too
import java.lang.*;
class abc
Runtime ob1;
ob1.exec("c:\\windows\\system32\\notepad.exe");
//i am getting a compile time error for this code
which cites that <identifier> required at line 6You need to put the exec call in a method or constructor. You can't just place code anywhere within a class.
You should also cal Runtime.exec just as I told you. It's a static method.
There are lots of examples if you google.
Kaj -
Runtim exec() method not working.....giving Exception
whts the code to use exec() method. i m using it as follows and also catching exception.
Runtime r=Runtime.getRuntime();
Process p=r.exec("java A");
code is giving IOException at runtime with error=2.Here is an example I used when I first needed to test the runtime.exec
import java.util.*;
import java.lang.*;
import java.io.*;
public class TestRuntime {
public static void main(String args[])
try
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("java A");
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<ERROR>");
while ( (line = br.readLine()) != null)
System.out.println(line);
System.out.println("</ERROR>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t)
t.printStackTrace();
}Are you waiting for the process to end before exiting your program? -
Problem to execute cvs command using Runtime.exec method
Hello,
I want execute this cvs command, with this options:
cvs -d :pserver:[email protected]:/home/cvs/cvsroot rlog -S -d "2007/05/01<now" Project
I tried to execute with Runtime.exec() :
Runtime.exec("cvs -d :pserver:[email protected]:/home/cvs/cvsroot rlog -S -d \"2007/05/01<now\" Project");
But I have an error because the smaller character is interpretate as a redirection, no as a smaller symbol.
How I can do to use this command with Runtime.exec ?
Thanks.
Regards.Sorry,
I had a typing mistake.
I want say:
Runtime.exec("cvs -d :pserver:[email protected]:/home/cvs/cvsroot rlog -S -d \"2007/05/01<now\" Project");
Regards. -
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.
-
The Runtime.exec methods doesn't work well on Solaris ???
I have two threads and I set the different running time.
I use Runtime.exec to a run the command and use Process to get the process.
It works properly in the windows2000 platform.
However, when I transfer the platform to Solaris...and run the program...
Two threads always at the same time....It is very wired....I always debug
for 2 days....
(at first I run "vmstat 1 2" command, later I change to "ls","rmdir"....etc,
all of them don't work.....
If I close the Runtime.exec..........Everything works well......)
And I study the API. I found this message...
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 Win32, or shell scripts. The created subprocess does
not have its own terminal or console.
Could someone share her/his experience.....:(
And if any other way I can run command inside java code instead of
Runtime.exec.....???
Please reply my mail to [email protected] I do appreciate your kindly &
great help!!!!!!!!
This is my code.......
import java.io.*;
import java.lang.*;
import java.util.*;
* <p>ServerThread1</p>
* <p>??�X???��?�D???�X???, "Vmstat 1 2".</p>
class ServerThread1 extends Thread{
private ServerAgent Sa;
public ServerThread1 (String Name, ServerAgent Sa){
super(Name);
this.Sa = Sa; file://Assign ServerAgent reference Sa
public void run(){
while(true){
try{
Thread.sleep(5000);
catch (Exception e){
System.out.println("ServerThread1 fails");
System.out.println("Thread1 is running.");
try {
Runtime rt1 = Runtime.getRuntime();
Process proc1 = rt1.exec("mkdir"); ------>If I close
rt1.exec , two threads works seperately...........:(
catch (Exception e) {
System.out.println("Thread1 Error");
class ServerThread2 extends Thread{
private ServerAgent Sa;
public ServerThread2 (String Name, ServerAgent Sa){
super(Name);
this.Sa = Sa;
public void run(){
while(true){
try{
Thread.sleep(15000);
catch (Exception e){
System.out.println("ServerThread2 fails");
System.out.println("Thread2 is running.");
try {
Runtime rt2 = Runtime.getRuntime();
Process proc2 = rt2.exec("vmstat 1 2"); ----->If I don't run
the rt2.exe, two threads work seperately....
catch (Exception e) {
System.out.println("Thread2 Error");
public class ServerAgent{
private Vector v1 = new Vector();
private Vector v2 = new Vector();
private Hashtable currentData = new Hashtable();
private static String startUpSwap = null;
private static String startUpMem = null;
public static void main(String[] arg) {
ServerAgent s = new ServerAgent();
ServerThread1 st1 = new ServerThread1("Thread1",s);
ServerThread2 st2 = new ServerThread2("Thread2",s);
st1.start();
st2.start();If I close the Runtime.exec..........Everything works
well......)You don't empty the output of the command, that blocks the process.
A citation from
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
Why Runtime.exec() hangs
The JDK's Javadoc documentation provides the answer to this question:
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.
Try out something like this:
String s;
try {
Process myProcess =
Runtime.getRuntime().exec("ls -l"));
DataInputStream in = new DataInputStream(
new BufferedInputStream(myProcess.getInputStream()));
while ((s = in.readLine()) != null) {
out.println(s);
catch (IOException e) {
out.println("Error: " + e);
}Another source of trouble under Unix is not having the correct permission for that user that executes the Java VM, which will be the permissions for the spawned subprocess. But this probably not the case, as you see something after exit.
Regards,
Marc -
Can MS Word Macros be executed with Runtime Exec.
When I open the Run Dialog box in Windows and type in - WINWORD.EXE c:\test.rtf /n /mFilePrint /mFileExit
the file - C:\test.rtf is printed using the Macros FilePrint and the application closes.
Now when I try to do the same in java using an instance of the Runtime class and pass the exec method a String[] with the same contents , it cannot find the executable WinWord.exe .
So i used the cmd /c option and specified the file name to open the file.
Runtime.getRuntime().exec("cmd /c \""+newfile+"\""); // newFile = String rep of path to the file But when i use /m which is a MS Word command line switch - The program compiles successfully and does nothing.Is there any way of executing the Macrohave a look at this here article:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html -
Short dump while executing job SM:EXEC SERVICES for EWA alert generation
Hello All,
I'm getting short dump error while executing job SM:EXEC SERVICES for EWA alert generation.I'm using EHP1@SP22 of Sol Man.
Please find the logs
Error in the ABAP Application Program
The current ABAP program "SAPLDSVAS_PROC" had to be terminated because it has
come across a statement that unfortunately cannot be executed.
The following syntax error occurred in program "RDSVASCABAP_TRANS__________073
" in include "RDSVASIABAP_TRANS__________073 " in
line 1782:
"Field "STATEMENT_SUMMARY001019" is unknown. It is neither in one of th"
"e specified tables nor defined by a "DATA" statement. "DATA" statement"
The include has been created and last changed by:
Created by: "SAP "
Last changed by: "SAP "
Error in the ABAP Application Program
The current ABAP program "SAPLDSVAS_PROC" had to be terminated because it has
come across a statement that unfortunately cannot be executed.
If anyone came across such kind of dump, please reply asap, due to this, i could not generate EWA report for R/3 system 6.04.
Thanks,
Anand.>
Anand Tigadikar wrote:
> Thx Paul, but i already did checked this note and its not solving my issue
Dear Anand,
Did you perform a complete service definition replacement for SDCC/SDCCN as described in the note?
These are manual steps you need to perform on the system and are not code corrections.
I would suggest you perform it, if you have not, and check the SDCCN logs to review the process ran cleanly.
Note: Please make sure SDCC_OSS is functioning and a connection to SAP can be made before
deleting the service definitions.
If you have already replaced the service defintions on the Solution Manager system, then no point doing it again. However checking a note and applying it are not the same thing. So I am uncertain if you replaced the service definitions or not. The dump you are getting in SM:EXEC SERVICES suggests its due to a problem with the service definitons. The recommendation is to replace them according to the process described in SAP Note 727998. If you have not done so please do so.
If you have successfully replaced the service definitions are you still getting the same dump, or has it possibly changed?
Regards,
Paul -
Setting value for attribute 'PO_NUMBER_SOLD' using setter method
Hi Experts,
I need to set the value of a screen field according to some condition. I am using setter method of this attribute to set the value but it is not getting changed.
I have written following code in DO_PREPARE_OUTPUT method of implementation class ZL_ZZBT131I_ZCREDITCHECK_IMPL using setter method of attribute
Get Referral Authorization Code
lv_val1 = me->typed_context->crechkresph->get_po_number( attribute_path = 'PO_NUMBER' ).
me->typed_context->crechkresph->set_po_number( attribute_path = 'PO_NUMBER'
value = ' ' ).
while debugging I found that in method set_po_number set_property method has been used:--
current->set_property(
iv_attr_name = 'PO_NUMBER_SOLD' "#EC NOTEXT
iv_value = <nval> ).
In set_property method following code is getting executed
if ME->IS_CHANGEABLE( ) = ABAP_TRUE and
LV_PROPS_OBJ->GET_PROPERTY_BY_IDX( LV_IDX ) ne IF_GENIL_OBJ_ATTR_PROPERTIES=>READ_ONLY.
if <VALUE> ne IV_VALUE.
if ME->MY_MANAGER_ENTRY->DELTA_FLAG is initial.
first 'change' -> proof that entity is locked
if ME->MY_MANAGER_ENTRY->LOCKED = FALSE.
if ME->LOCK( ) = FALSE.
return.
endif.
endif.
flag entity as modified
ME->MY_MANAGER_ENTRY->DELTA_FLAG = IF_GENIL_CONTAINER_OBJECT=>DELTA_CHANGED.
endif.
ME->ACTIVATE_SENDING( ).
change value
<VALUE> = IV_VALUE.
log change
set bit LV_IDX of ME->CHANGE_LOG->* to INDICATOR_SET.
endif.
else.
check if it is a real read-only field or a display mode violation
assert id BOL_ASSERTS subkey 'READ-ONLY_VIOLATION'
fields ME->MY_INSTANCE_KEY->OBJECT_NAME
IV_ATTR_NAME
condition ME->CHANGEABLE = ABAP_TRUE.
endif.
and in debugging I found that if part ( ME->IS_CHANGEABLE( ) = ABAP_TRUE and
LV_PROPS_OBJ->GET_PROPERTY_BY_IDX( LV_IDX ) ne IF_GENIL_OBJ_ATTR_PROPERTIES=>READ_ONLY) fails and hence else part is getting executed and hence my field a real read-only field or a display mode violation is happening according to comments in code.
What shall I do so that I would be able to change the screen field value?
Any help would be highly appreciated.
Regards,
VimalHi,
Try this:
data: lr_entity type cl_crm_bol_entity.
lr_entity = me->typed_context->crechkresph->collection_wrapper->get_current( ).
lr_entity->set_property( iv_attr_name = 'PO_NUMBER' value = '').
Also, make sure the field is not read-only.
Regards
Prasenjit -
How to use secondary method in workflow?
Hi friends,
can anyone plz let me know how to use secondary methods in workflow? it would be helpful if u explain with an example..
thanks and regards,
Arun.SHi Arun Kumar,
The Sec Method can be used in the user decision step. The secondary methods are executed along with the user decision step. You have 3 options. Either execute a secondary method before executing the user decision step or after execution of user decision step or while executing the user decision.
For this define the methods either in Methods before execution of workitem execution to execute it before user decision step or Methods after execution of workitem so as to execute it after the execution of user decision.
In order to execute a method along with user decision step execution use secondary methods (amodal call.)
Let me know if you have any queries.
Regards,
Raj -
Java's Runtime.exec() method
When you shell out to java's Runtime.exec() method, are the process name and arguments the same for the child process that is spawned.
We see duplicated processes about the time when our logs tell us this command was run. However, we cannot seem to reproduce this. Has anyone else seen anyone this before?That's what I though too. But check this out . . .
Our code looks as follows:
private Runtime rt;
private Process p;
rt = Rutime.getRuntime();
p = rt.exec(command);
This exec() call creates a new process, which is a child of the java process that runs this command. The final process looks like the "command" string that is passed to the exec() method call. In our case, the command is a call to the /usr/bin/mail utility to send out faxes and emails.
We ran a very tight loop executing the rt.exec() call over and over. What we found was that for a minor fraction of a second, the newly created process looks just like the original process including the same arguments. However, the PID's indicated that one process was the child of the other. This is why it looked like we had 2 of the same processes. WILD!
Thanks guys! -
In SQLScript, how to use EXEC to call another procedure with parameters in procedure?
Hi experts,
In SQLScript, How to use EXEC to call another procedure with input and output parameters in procedure?thanks very muchHi Sagar,
thank you! I generate another procedure with an input parameter and an output parameter in a procedure. Then i need to call the generated procedure using EXEC. Here is my code:
create procedure ftest1(out sum_num bigint)
as
begin
declare fa_output bigint;
declare v_sql_drop varchar(200);
declare v_sql varchar(500);
declare cursor c_cursor1 for select num from TABLE1;
--v_sql_drop := 'drop procedure fe';
--exec v_sql_drop;
v_sql := 'create procedure fe(in i_num bigint,out o_num bigint) as begin';
v_sql := :v_sql || ' o_num := :i_num * 2 + :i_num * :i_num;';
v_sql := :v_sql || ' end';
exec v_sql;
open c_cursor1;
for c_item as c_cursor1 do
exec 'call fe(c_item.num,o_num=>fa_output)';
if sum_num is null then
sum_num := fa_output;
else
sum_num := :sum_num + fa_output;
end if;
end for;
close c_cursor1;
end;
The underline code is using exec to call the generated procedure. But this method cannot work. Any suggestion? thanks again!
Maybe you are looking for
-
I need to pull a hard drive from a power mac g4 what enclosure will work?
I need to pull a hard drive from a power mac g4 what enclosure will work?
-
How to do manual back up in conjunction with T.M.
hello i want to use time machine to perform ongoing back ups of my entire account. however, there is one grouping of files that has to be manually dragged to my back up drive on a daily basis. my question is: if time machine backs up account until dr
-
does anyone successfully connected a VCR to an Imac so as to record the screen image ? I have tried using the mini s-video adapter supplied by apple to connect to my VCR via a switchable s-video to scart adapter but with no success. I want to record
-
AT&T Orders Only - Shipping Status
I ordered 3 i4s from AT&T online at 6:30am EDT on the 15th. Also added a line for my son at AT&T store at 12:30pm the same day. Both orders say "in progress" as of 10:09 am EDT on Fathers Day. Anyone seeing their AT&T orders shipped yet?
-
So I have the original disc's but I'm thinking I need something more because I was not able to deactivate the program when my computer crashed. I reloaded Windows from scratch and lost my files.