Runtime exec MFC console program

I'm trying to launch an MFC console program with some parameters
but it doesn't work
no exeception (but it looks like it has never been launched)
I made a program which is not MFC that works in the same configuration
But I need to launch an MFC one
could some one help me??

I found the solution
it works with jdk 1.3 (3 parameters)
when you launch the exe you must specify
the working path
runtime.exec("path/exename",null,"workingDirectoryPath");

Similar Messages

  • Runtime.exec(command)

    hi experts,
    I am trying to execute a set of commands from java program
    eg: from command prompt
    java CommandExecutor c:\winnt\notepad.exe c:\some.exe c:\onemorecommand.exe
    and inside the CommandExecutor main method..
    public static void main(String []arg)
    for(i = 0; i < arg.length; i++)
    Runtime.getRuntime().exec(arg(i));
    the above code is executing all the command one after the other, but I want to execute the above commands squentially, i.e I want to execute the second command only after finishing the first command and the third after finishing the second and so on depending upon the arguments passed, how can I acheive this...
    I have tried to use the Process which is returned by the exec(arg) method but the exitValue() returns same value before execution and after execution.
    thanks,
    krishna

    This is the code I use for this very purpose and it works great. Here you go:
    * Wrapper for Runtime.exec
    * No console output is generated for the command executed.
    * Use <code>process.getOutputStream()</code> to write data out that will be used as
    * input to the process. Don't forget to include <code>\n</code> <code>\r</code>
    * characters the process is expecting.
    * Use <code>process.getInputStream</code> to get the data the process squirts out to
    * stdout.
    * It is recommended to wrap this call into a seperate thread as to not lock up the
    * main AWT event processing thread. (generally seperate threads are needed for both
    * the STDOUT and STDIN to avoid deadlock)
    * @param theCommand fully qualified #.exe or *.com command for windows etc.
    * @see   exec, shell, command, cmd, forDOS, forNT
    public static Process exec( String theCommand, boolean wait )
         Process process;
         try
              process = Runtime.getRuntime().exec( theCommand );
         catch ( IOException theException )
              return null;
         if ( wait )
              try
                   process.waitFor();
              catch ( InterruptedException theInterruptedException )
         return process;
    }

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

  • Calling c code that calls mount using runtime.exec

    I'm having an issue using mount calls when I execute a c program through runtime.exec(). The program attempt to search all drives for data and display them for the user. When the specified data isn't found, the user is given the option to search again. When the user repeatedly does this the program reaches a point where it hangs. It appears to be due to the mount calls during the search. Anyone know why this may be happening and how to prevent it from occurring?

    Not sure, but this may help:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Runtime.exec() process output

    I am having strange problems with the output from a program I am executing with Runtime.exec(). This program takes voice input, and generates text output on the commandline. For some reason, I do not see any of the output until the program exits, then everything is displayed. My code is below, any help would be greatly appreciated!
    Thanks,
    Deena
    import java.io.*;
    import java.util.*;
    //Reads and prints the output streams from an executing process
    class ProcessStream extends Thread{
         InputStream is;
         String type;
         ProcessStream(InputStream is, String type){
         this.is = is;
         this.type = type;     //type of output stream, e.g. stdout or stderr
         public void run(){
         try{
              BufferedReader br = new BufferedReader(new InputStreamReader(is));
              String line=null;
                   //read and display the output stream of an executing process
              while ((line = br.readLine()) != null){
              System.out.println(type + ">" + line);
         } catch (IOException ioe){
         System.err.println(ioe);
    //Interface to TalkBack.exe
    public class JTalkBack{
         public static void main(String[] args){
         try{
              String arg="TalkBack.exe -noTTS -noReplay";     //program to execute
              //arguments to program
              for(int i=0; i<args.length; i++){
                   arg+=" "+args;
              //execute the program and get an object representing the process
              Process p=Runtime.getRuntime().exec(arg);
              //create stream processors for stdout and stderr of the process
              ProcessStream error = new ProcessStream(p.getErrorStream(), "ERROR");
              ProcessStream output = new ProcessStream(p.getInputStream(), "OUTPUT");
              //start the stream processors
              error.start();
              output.start();
              //wait for the process to finish and get its exit value
              int exitVal = p.waitFor();
         System.out.println("ExitValue: " + exitVal);
         catch (Throwable t){
         System.err.println(t);

    I have something similar and it works. The only difference is that I:
    1. used a BufferedInputStream instead of the BufferedReader, which means bis.available() and bis.read(buffer) were used instead of .readLine(bis)
    2. Didn't print to stdout, but instead fired a proprietary MessageEvent with the string in it to all MessageListeners (good for use with java.util.logging)
    3. Didn't (yet) put the input streams in different threads.
    Maybe it is related to the fact that you are printing directly back to the System.out again? Does each process in Java get its very own standard out? I don't know.
    It's ugly and convoluted, but maybe a snippet of my code will help...
    (in run)
    Thread myThread = Thread.currentThread();
      try {
        proc = r.exec("my_secret_process.exe -arg arg");
        is = new BufferedInputStream(proc.getInputStream());
        while (thread == myThread) {
          int iRead = 0; //how many bytes did we read?
          //message stream check
          if(is.available() > 0) {
            iRead = is.read(buf);
            msg = "\n"+new String(buf, 0, iRead);
            this.fireMessageArrived(new MessageEvent(this, msg));
         } //end while
       } catch(Exception e) {
          System.out.println("Argh.  Barf.");
      Tarabyte :)

  • Runtime.exec() - how to open new window for new program?

    Hi,
    I have searched through the forums but haven't found an answer to this one yet. I am using runtime.exec() to start up a new java program. At first I thought it wasn't running properly but, after checking task manager, I have discovered that the new program I open runs, it is just completely invisible to me. I am wondering how I can get the new program to run in a command window or something where I can monitor it.
    Thank you for your help,
    Drew

    Thank you all. After trying to figure out why the start command wouldn't work in the runtime.exec() call(not an executable - I am a dolt), I tried putting it in a batch file and it worked perfectly. Thanks for your help,
    Drew

  • Runtime exec problem to execute a C program

    Hi,
    I've spend lot of time trying to find a solution without success...
    My aim is to run a C program from a java application under linux. My C code is the following:
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    main(int argc, char **argv){
    printf("hello world \n");
    Once compiled I run my java application wich run the binary through a runtime.exec().
    I followed the example given by
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    with the same input gobblers and threads.
    For some reason it doesn't work: nothing comes out...
    When I call "ls" instead of my binary it works perfectly!
    WHY??
    Any help would be greatly appreciated!

    Thanks for the reply.
    Yes it seems that JNI could be a solution, but it looks a bit complicated an maybe not so well adapted to my purpose.
    The executables I want to execute from my java application don't need any arguments.
    If JNI is really the only way I'll try to use it but is there any good reason why runtime exec doesn't work? It is supposed to execute any executable isn't it?
    cheers

  • Strange problem when a c++ program is triggered by Runtime.exec()

    I am working in linux system. I have 2 programs:
    1. one is a c++ program e.g. AAA. In this program, i use "system("gcc ...")" to call gcc to do some internal processing
    2. the other is a java program BBB. In this program, i use Runtime.exec("AAA") to run program AAA.
    case 1
    if I run c++ program AAA directly, everything goes well, gcc call via "system" is successful.
    case 2
    if I run java program BBB to trigger AAA indirectly, the AAA can be executed, but the system call (gcc call inside AAA) is failed.
    so, what is wrong? any hints? what is the solution to make case #2 work? I just want to use BBB to trigger AAA, and the system call should also be successful.
    thanks in advance for your help!

    "...but the system call (gcc call inside AAA) is failed."
    Isn't terribly descriptive, but I'm guessing that it complains it can't find gcc?
    If that's the case then it's because the call to Runtime.exec() runs the code in a shell with no idea where anything is, whereas when you run the C++ code straight it is running in the shell you kicked it off in. Something along those lines anyway.
    Someone else'll be able to tell you how to get it to work. I'm sure I've seen this sort of problem here several times.

  • Runtime.exec does not execute my program, but executes "ls"

    I am trying to run an exe from a Java program.
    The program that I want to run is an output of a gcc -o ICDDATA ICDdata.c
    Now when I use the Runtime.exec() and execute "ls", "cat" it is working fine without any errors.
    But when i try to give the file(ICDDATA) that was created with the gcc, it generates an error code of "11" or "10" and exits the process.
    Could anyone please let me know the reason why this is happenig and suggest and appropiate solution for this.

    When I give ICDDATA at the prompt, it is executing perfectly fine.
    But only when it is run inside the Java program its giving the error code 10.
    Here is the source code:
    ======================================
    public class InvokeInterface {
         This method takes two parameters and accordingly invokes one of the
         interface (ICD / Value).
         @Input : String, String
         @Return : void
         static void executeInterface(String processName, String debugOption)
         throws java.io.IOException     {
              String commandToExecute=". / ";
                   // The command that has to be passed to the Shell.
              if(processName.equals("ICD"))
                   commandToExecute="ICDDataRefresh";
              if(processName.equals("VALUE"))
                   commandToExecute="ValueDataRefersh";
              commandToExecute += " "+debugOption;
              System.out.println("..."+commandToExecute);
              Runtime runtime = Runtime.getRuntime();
              Process proc = runtime.exec(commandToExecute);
                   try {
                        if (proc.waitFor() != 0) {
                        System.err.println("exit value = " +
                        proc.exitValue());
              catch (InterruptedException e) {
                   System.err.println(e);
    ==========
    Thanks in Advance
    Ram

  • Runtime.exec() makes program act weird

    Hello
    I have a problem with the runtime.exec() command?
    I have created a program in vb.net with a tcpClient that opens a stream to a server.
    When i execute the program myself it works fine, but when i run it through my java applet with runtime.exec() its suddenly hangs reading the stream?
    I can't make it work, and its so weird that the program reads the stream several times and then just hangs, even though i can see in wireshark that packets are recieved.
    Please help anyone who might know how to solve this :)

    Read and implement the recommendations in all sections of [When Runtime.exec() won't|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html].
    db

  • Runtime.exec() + getOutputStream() +write+me program=hang

    I'm trying to write to the standard input of an external prorgram by using Runtime.exec() and writing to the outputstream of the process it creates. I write to the standard in and then wait for that process to finish using waitFor() but it just hangs there. Is there something special to do before writing the data?
    There is nothing funky about my code, it's just basic stuff.
    OutputStream out =process.getOutputStream();
    out.write(data);
    out.flush();
    out.close();
    process.wairFor();

    Do you really know
    1. That the process got the data and processed it?
    2. That the process exited and you are still hanging?
    Sorry if I'm just stating the obvious, but is the other process perhaps waiting for an end-of-line or end-of-input?
    Finally, you didn't say what the other process technology is, but I've had some surprises when attempting to work between java and other technologies. Example: Other process was LEX, which uses a Windows flag to check for character or block input. Flag was set in a surprising manner when java was the source, and my LEX blocked forever.

  • How to display Runtime.exec() command line output via swing

    Hi all, I'm new to java but have a pretty good understanding of it. I'm just not familiar with all the different classes. I'm having trouble capturing the output from a command I'm running from my program. I'm using Runtime.exec(cmdarray) and I'm trying to display the output/results to a JFrame. Once I get the output to display in a JFrame, I'd like it to be almost like a java command prompt where I can type into it incase the command requires user interaction.
    The command executes fine, but I just don't know how to get the results of the command when executed. The command is executed when I click a JButton, which I'd like to then open a JFrame, Popup window or something to display the command results while allowing user interaction.
    Any examples would be appreciated.
    Thank you for your help in advance and I apologize if I'm not clear.

    You can get the standard output of the program with Process.getInputStream. (It's output from the process, but input to your program.)
    This assumes of course that the program you're running is a console program that reads/writes to standard input/output.
    In fact, you really should read from standard output and standard error from the process you start, even if you're not planning to use them. Read this:
    When Runtime Exec Won't

  • 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

  • Using console program from java swing

    Can anyone please tell me if the following is possible and how to do it. I want to create a gui for mencoder and so for example i will be wanting toexecute mencoder from the swing app to find out the the auto crop values so i can visually display them. As well when i am actually encoding the files i want to somehow use the progress output from the program and visually display it in swing using a progress bar. I am just quiter sure where to start or even what doing this is called. I know it is possible just now how.
    Cheers
    Damian

    You can use Runtime.exec or ProcessBuilder to run external programs.
    If you do that, I'd suggest trying to use arguments to mencoder that change its console output to be easier to parse. I don't know if such an option exists, but many programs built for the command line provide such options, and mencoder certainly provides a lot of options. Block off a few weeks and you might make your way through a third of the manual.
    Also the mplayer/mencoder suite may provide a C library. I don't recall. If it does, you might be able to use JNI.

  • Java.lang.Runtime.exec problem in ubuntu 9.10

    Hi:
    I tried to run some command in the java code , for example "grass64 -text /home/data/location", this command works well in the terminal, however when I call it in the java code I got some excepetions.
    My code is :
    public class Grass {
         public static String grassBatJob="GRASS_BATCH_JOB";
         public void run(String cmd,String jobPath) {
              //set the environments variables
              Map<String, String> env=new HashMap<String, String>();
              env.put(grassBatJob, jobPath);
              String gisDataBase="/home/kk/grass/GrassDataBase";
              String location="spearfish60";
              String mapset="PERMANENT";
              cmd=cmd+" "+gisDataBase+"/"+location+"/"+mapset;
              CommandLine line=new CommandLine(cmd);
              //the real cmd should be >>grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT
              System.out.println("start line=="+line.toString());
              DefaultExecutor de=new DefaultExecutor();
              try {
                   int index=de.execute(line,env);
                   System.out.println(index);
              } catch (ExecuteException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              String jobPath=Grass.class.getResource("grass.sh").getFile();
              new Grass().run("grass64 -text", jobPath);
    The real cmd I want to execute is "grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT" with the envrionment variable "GRASS_BATCH_JOB=jobPath",it works well in the ternimal ,however in my application I got the exception"
    java.io.IOException: Cannot run program "grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT": java.io.IOException: error=2, No such file or directory
         at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
         at java.lang.Runtime.exec(Runtime.java:593)
         at org.apache.commons.exec.launcher.Java13CommandLauncher.exec(Java13CommandLauncher.java:58)
         at org.apache.commons.exec.DefaultExecutor.launch(DefaultExecutor.java:246)
         at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:302)
         at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:149)
         at org.kingxip.Grass.run(Grass.java:27)
         at org.kingxip.Grass.main(Grass.java:38)
    Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
         at java.lang.UNIXProcess.<init>(UNIXProcess.java:148)
         at java.lang.ProcessImpl.start(ProcessImpl.java:65)
         at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
         ... 7 more
    I wonder why?

    Thanks for all of your reply, and now I can run the command, however I met some problems when I tried to get the result of the exec.
    The core codes are shown below:
    String cmd="g.version";
    String[] exe={"bash","-c",cmd};
    Process p1=Runtime.getRuntime.exec(exe,env); // the env has been set
    GrassThread outThread=new GrassThread("out", p1.getInputStream());
    outThread.start();
    GrassThread errorThread=new GrassThread("error", p1.getErrorStream());
    errorThread.start();
    int exitVal = p1.waitFor();
    String resu=outThread.sb.toString();
    System.out.println("==========the output start========");
    System.out.println(resu);
    System.out.println("==========the output end========");
    System.out.println("ExitValue: " + exitVal); //------------------> line one
    public class GrassThread extends Thread{
         public StringBuffer sb=new StringBuffer();
         public GrassThread(String type,InputStream is) {
              this.type=type;
              this.is=is;
         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);
                        sb.append(line).append("\r");  // ----------------------------> line two
    }I define a StringBuffer in the GrassThread to save the output (see the code where I marked by "line two"), and when the process complete, I check the StringBuffer to get the output (see code where I marked by "line one"), however the output in the console of the IDE are :
    ----------- output in the console of the IDE start -------------
    ==========the output start========
    ==========the output end========
    ExitValue: 0
    out>GRASS 6.4.0RC5 (2009)
    ----------output in the console of the IDE end--------------------
    I can not understand, in the code "line one", I first get the output using "System.out.println(resu);",then I print the exitvalue,but why the order of the output in the console is not what I expected?
    Another question, the code above assume the output can be got from the Process's getInputStream, however sometimes the output maybe come from the Process's getErrorStream, so how to handle it?
    Edited by: apachemaven on 2010-3-5 ??5:38

Maybe you are looking for

  • ProForma Invoice Problem for srvices

    Hi my client has a report which is working properly for products but in case of services material its showing/picking complete billed values & quantities? My client want it be same as products (whatever delivered).In this case from where it would be

  • Outlook 2011 for mac daylight savings time issue

    Hello, I have a problem in my company where after daylight savings time meetings are shown an hour off in the calendar, but in the body of the meeting the time seems fine. The real problem is when after updating the meeting from it's body (just press

  • Appleworks not opening

    hello. i'll try to make up for my only other (rather hasty) post...hopefully this will be coherent enough to elicit a solution! here's a general timeline of my problem– hopefully someone can see a flaw or step i've missed: i've used appleworks for as

  • Rlogin and subsequent IO communication issue

    My application has to use runtime.exec to login to a remote server from a unix environment. The call to echo out the response hangs. Here is the code             Process itests =                 Runtime.getRuntime().exec("rlogin -l uname tgtSrver ");

  • Macbook briefly freezes then comes back to life during sessions

    My Macbook, which I've owned since September 2006, is starting to suffer from brief freezes. For a few seconds, all operations freeze on the screen (the cursor is still movable), then it's followed by a few seconds of the spinning wheel, and then thi