如何向现有进程发送另一个命令?

How to send another command to an existing process?

我得到以下启动 minecraft 服务器的代码:

public class App {

    public static void main(String...args) throws Exception {
        final ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.directory(new File("C:/Users/trudler/Desktop/New folder (4)/"));
        processBuilder.command("java", "-jar", "server.jar");
        Process process = processBuilder.start();

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;

        System.out.printf("Output of running %s is:", Arrays.toString(args));

        while ((line = br.readLine()) != null) {
          System.out.println(line);
        }
    }
}

我想做每日备份,所以我需要每天发送一个 "stop" 命令,以确保在我做备份时文件不会被触及(并且 "start"之后再次服务器)。

我该怎么做?

我用 processBuilder.command("stop"); 尝试过,但似乎不起作用。

我认为您想向现有进程发送命令,所以我认为这就是您要查找的内容:

Execute external program using ProcessBuilder and provide input

public class App{

   public static void main(String... args) throws Exception {
      while (true) {
         Process process = Example.startMinecraft(args);
         // Stops for sixty seconds
         Thread.sleep(1000 * 60);

         BufferedWriter out = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
         out.write("stop");

         // Wait for the process to stop
         process.waitFor();

         // Now start your Backup
         Process backupProcess = Example.startBackup();
         backupProcess.waitFor();

         // After your backup completed your minecraft server will start again
      }

   }

   private static Process startMinecraft(String... args) throws IOException {
      final ProcessBuilder processBuilder = new ProcessBuilder();
      processBuilder.directory(new File("C:/Users/trudler/Desktop/New folder (4)/"));
      processBuilder.command("java", "-jar", "server.jar");
      Process process = processBuilder.start();

      InputStream is = process.getInputStream();
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);

      Thread t1 = new Thread(() -> {
         try {
            String line;
            System.out.printf("Output of running %s is:", Arrays.toString(args));
            while ((line = br.readLine()) != null) {
               System.out.println(line);
            }
         } catch (IOException e) {
            // Do something when the Exception is thrown
         }
      });
      t1.start();

      return process;
   }

   private static Process startBackup(){
      // Here you have to build your backup process
   }
}

如果您使用的是 linux 机器,我建议您改用 /etc/init.d/ 中的一些脚本,并在 cron 作业中使用此脚本使用重启命令。