2

我想执行一个简单的命令,它可以在 shell 中工作,但不能在 Java 中工作。这是我要执行的命令,效果很好:

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

这是我从 Java 中执行的代码,试图运行这个命令:

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是否有可能在程序运行后将其杀死?

为什么这不起作用?

4

4 回答 4

2

我不确定我是否记错了,但据我所知,您正在生成命令但从未将它们传递给“执行”方法......您正在执行“”。

尝试使用 Runtime.getRuntime().exec(commands) =)

于 2008-12-18T16:42:50.707 回答
1

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

然后从 Java 我只运行脚本,它工作正常,如下所示:

公共 void startSOfficeService() 抛出 InterruptedException,IOException {
        //首先我们需要检查soffice进程是否正在运行
        字符串命令 = "pgrep soffice";
        进程进程 = Runtime.getRuntime().exec(commands);
        //需要等待这条命令执行
        int 代码 = process.waitFor();

        //如果我们从 readLine 得到任何东西,那么我们知道进程正在运行
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        if (in.readLine() == null) {
            //没有返回,那么我们应该执行该过程
            进程 = Runtime.getRuntime().exec("/etc/init.d/soffice.sh");
            代码 = process.waitFor();
            log.debug("soffice 脚本启动");
        } 别的 {
            log.debug("soffice 脚本已经在运行");
        }

        附寄();
    }

我也通过调用这个方法杀死了 soffice 进程:

公共无效 killSOfficeProcess() 抛出 IOException {
        if (System.getProperty("os.name").matches(("(?i).*Linux.*"))) {
            Runtime.getRuntime().exec("pkill soffice");
        }
    }

请注意,这只适用于 Linux。

于 2009-01-21T10:07:55.303 回答
0

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

在您的 Java 代码中,shell 永远不会看到参数,因此不需要额外的双引号(用反斜杠转义)——它们可能会使 soffice 感到困惑。

这是去掉了多余引号的代码(并添加了一个分号)

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,也没有测试过这个!)

于 2009-02-18T04:19:10.697 回答
0

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

或者只是转义引号也可以。我们将这样的命令提供给 ant 脚本,最终以 exec 调用结束,就像你上面所说的那样。我还建议每 500 次左右的转换重新启动该过程,因为 OOO 无法正确释放内存(取决于您运行的版本)。

于 2009-02-19T01:06:52.367 回答