【问题标题】:shell process java synchronizationshell进程java同步
【发布时间】:2012-06-28 11:20:07
【问题描述】:

我想从 java 程序运行一个 shell 脚本。这个 shell 脚本调用了一个系统库,它需要一个大文件作为资源。

我的 java 程序为文档中的每个单词调用此脚本。如果我使用 Runtime.exec() 一次又一次地调用此脚本,则所花费的时间非常长,因为资源加载需要大量时间。

为了克服这个问题,我想编写如下的 shell 脚本(使其在后台连续运行):


count=0

while count -lt 10 ; do

  read WORD

  //execute command on this line

done

我需要在我的 java 程序中检索命令的输出并进一步处理它。 我应该如何编写 I/O 操作来完成这项任务?

我尝试将单词写入进程的输出流并从进程的输入流中读回输出。但这不起作用并引发损坏的管道异常。


try {

    parseResult = Runtime.getRuntime().exec(parseCommand);

    parsingResultsReader = new BufferedReader(new InputStreamReader (parseResult.getInputStream()));

    errorReader = new BufferedReader(new InputStreamReader (parseResult.getErrorStream()));

    parseResultsWriter = new BufferedWriter(new OutputStreamWriter((parseResult.getOutputStream())));

} catch (IOException e) {

            e.printStackTrace();

}

parseResultsWriter.write(word);

parseResultsWriter.flush();

while ((line = parsingResultsReader.readLine()) != null) {

     // capture output in list here

}

请帮助解决这个问题

【问题讨论】:

  • “shell”进程是否需要独立于VM,还是VM可以自己启动?

标签: java shell io broken-pipe


【解决方案1】:
//execute command on this line

这个命令是一个单独的程序吗?然后它将针对每个单词启动,因此您将只摆脱轻量级的 shell 进程。 您必须学习如何同时为多个单词运行重量级命令。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 2021-11-06
    相关资源
    最近更新 更多