简体   繁体   中英

Exec runtime on Java EE servers

For some reasons on my project I need to run this command "gcc file.c -o file.exe" on a Java EE server, I used this java code

try {  
        Runtime runtime = Runtime.getRuntime();
         String[] cmd={"cmd.exe","/C gcc " + a +".c" + " -o "+b};
         Process p = runtime.exec(cmd,null,null );
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            String line = null;
            try {
               while((line = reader.readLine()) != null) {
                       System.out.println(line);
                }
            } finally {
                reader.close();
            }
        } catch(IOException ioe) {
            ioe.printStackTrace();

        }


        } 
    catch (Exception e) {System.out.println("erreur d'execution"); }

}

the command works perfectly on cmd and this code works perfectly on a Java application and I get my output(.exe) and my the errors.

Once I try to deploy it on a server later (using a JBoss server) nothing happened. I tried later to just execute cmd from the server nothing happened too. So it is kind of a Java EE server problem.

How can I fix it? Are there other servers such as Tomcat that can execute this code?

Firstly, spawning processes using runtime.exe violates the EJB spec for numerous reasons. Therefore, you have the gun in one hand and the bullets in the other as they say and you could easily shoot yourself in the foot if you don't understand the implications of doing this.

You could move this code into a Servlet (still deployed to your JavaEE container of choice) to be more spec compliant but you still need to understand how it will all play out in a clustered environment should your app ever be run in such. If you need the process to interact in the scope of a DB transaction then you have even more problems but lets assume that's not one of your requirements.

With those warnings out of the way your current approach has a major flaw that will lead to indiscriminate thread deadlocks. When you start a process you have to manage the STDOUT/STDERR streams in their own threads so that the buffers will drain without the possibility of a deadlock between the two. You are not doing that here, you are simply reading from the InputStream from the same thread you started your process from. That could very well be what's going on here when you say - 'nothing happens'. Have you taken a thread dump of your server process?

To avoid such deadlocks, and they will happen at some point trust me, use a pattern like that which is outlined here: Why runtime.exec() hangs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM