2008-12-18 356 views
2

我想优先执行一个简单的命令,该命令在shell中运行但不能在Java中运行。 这是我要执行的命令,它工作得很好:从Java启动OpenOffice服务(soffice)的问题(命令在命令行中运行,但不是从Java运行)

soffice -headless "-accept=socket,host=localhost,port=8100;urp;" 

这是我从Java试图运行此命令excecuting代码:

String[] commands = new String[] {"soffice","-headless","\"-accept=socket,host=localhost,port=8100;urp;\""}; 
Process process = Runtime.getRuntime().exec(commands) 
int code = process.waitFor(); 
if(code == 0) 
    System.out.println("Commands executed successfully"); 

当我运行这个程序,我得到“命令执行成功”。 但是程序结束时该进程没有运行。 JVM在运行后可能会杀死程序吗?

为什么不能正常工作?

回答

1

我想说我是如何解决这个。 我创建了一个基本上为我运行soffice命令的sh脚本。

然后从Java我只是运行该脚本,它工作得很好,是这样的:通过调用此方法

 
public void startSOfficeService() throws InterruptedException, IOException { 
     //First we need to check if the soffice process is running 
     String commands = "pgrep soffice"; 
     Process process = Runtime.getRuntime().exec(commands); 
     //Need to wait for this command to execute 
     int code = process.waitFor(); 

     //If we get anything back from readLine, then we know the process is running 
     BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); 
     if (in.readLine() == null) { 
      //Nothing back, then we should execute the process 
      process = Runtime.getRuntime().exec("/etc/init.d/soffice.sh"); 
      code = process.waitFor(); 
      log.debug("soffice script started"); 
     } else { 
      log.debug("soffice script is already running"); 
     } 

     in.close(); 
    } 

我也杀soffice过程:

 
public void killSOfficeProcess() throws IOException { 
     if (System.getProperty("os.name").matches(("(?i).*Linux.*"))) { 
      Runtime.getRuntime().exec("pkill soffice"); 
     } 
    } 

请注意,这只是在Linux中工作。

2

我不确定我是否没有弄错,但据我看到,您正在生成命令,但从未将它们传递给“执行”方法......您正在执行“”。

使用调用Runtime.getRuntime尝试()。EXEC(命令)=)

0

我相信你没有正确处理引用。原始的sh命令行包含双引号以防止shell解释分号。在soffice过程看到它们之前,壳将它们剥离。

在您的Java代码中,shell永远不会看到参数,因此不需要额外的双引号(使用反斜杠转义) - 而且它们可能会造成混淆。

下面是与剥离的额外引号的代码(在抛出一个分号)

String[] commands = new String[] {"soffice","-headless","-accept=socket,host=localhost,port=8100;urp;"}; 
Process process = Runtime.getRuntime().exec(commands); 
int code = process.waitFor(); 
if(code == 0) 
    System.out.println("Commands executed successfully"); 

(免责声明:我不知道Java和我没有测试过这一点)

0

"/Applications/OpenOffice.org\ 2.4.app/Contents/MacOS/soffice.bin -headless -nofirststartwizard -accept='socket,host=localhost,port=8100;urp;StartOffice.Service'"

或者干脆逃离报价也可以。我们向这样的命令提供一个蚂蚁脚本,最终以上面的exec调用结束。我还建议每500次转换重新启动一次进程,因为OOO没有正确释放内存(具体取决于您运行的版本)。