【问题标题】:Send command to running process向正在运行的进程发送命令
【发布时间】:2021-04-06 20:31:25
【问题描述】:

是否可以像下面的示例那样向正在运行的进程发送命令?
你会怎么做呢?

Process p = pb.start();

【问题讨论】:

    标签: java process


    【解决方案1】:

    很可能不是您想要实现的目标,但是是的,您可以使用 Process.getOutputStream() 与正在运行的 Process 进行通信

    【讨论】:

      【解决方案2】:

      对于读取和写入命令行的进程,使用p.getOutputStream() 向进程发送数据,使用p.getIntputStream() 从进程读取数据。对于 GUI 进程,您需要本机代码来根据操作系统发送消息。

      编辑: 正在读取/写入控制台的进程的示例代码:

      Process process = pb.start();
      
      // process stdout
      Scanner stdout =  new Scanner(
          new BufferedReader(
              new InputStreamReader(process.getOutputStream())));
      
      // process stdin
      PrintWriter stdin = new PrintWriter(
          new BufferedWriter(
              new OutputStreamWriter(process.getInputStream())), true);
      
      // sending commands to the process
      stdin.println("command1");
      stdin.println("command2");
      stdin.println("command3");
      
      // reading process output
      while (stdout.hasNextLine()) {
          System.out.println("Process output: " + stdout.nextLine());
      }
      

      【讨论】:

      • 我该怎么做:/?已经尝试过但 in.transferTo(out);说方法对于Inputstream的类型未知...paste.ggc-project.de/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-06
      相关资源
      最近更新 更多