bash中java程序的linux管道输入

piztneat  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(295)

我有一个java程序:

public class ProcessMain {
    public static final void main(String[] args) throws Exception {        

        Scanner keyboard = new Scanner(System.in);
        boolean exit = false;
            do
            {   if(keyboard.hasNext()){
                    String input = keyboard.next();
                    System.out.println(input);
                    if( "abort".equals(input)){
                    ABORT();
                    exit = true;
                    }
                }else{
                    System.out.println("Nothing");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }while (!exit);
        }

    private static void ABORT(){
        System.out.println("ABORT!!!!");
    }
}

在linux中,脚本:

rm testfifo
mkfifo testfifo
cat > testfifo &
echo $!

java -cp "Test.jar" com.example.ProcessMain < testfifo

终端a运行脚本,每5秒打印一次“nothing”。然后终端b执行echo“abort”>testfifo,但是程序不能显示abort,它仍然每5秒显示一次。
请帮忙!!

mftmpeh8

mftmpeh81#

如果您只需要外部触发器来停止当前处理。您可以创建一个信号量文件,并在另一个进程创建它时立即停止。
请参见以下代码段。

// it will check for the file in the current directory
File semaphore = new File("abort.semaphore");
semaphore.deleteOnExit();
System.out.println("run until exist: " + semaphore);
while (!semaphore.exists()) {
    System.out.println("Nothing");
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
System.out.println("ABORT!!!!");

只要文件 abort.semaphore 不存在,程序将打印到控制台并等待5秒钟。
在linux上,您可以使用一个信号处理程序并发送一个 SIGABRT 到正在运行的进程。
下面的代码段使用内部专有api

import sun.misc.Signal;
import sun.misc.SignalHandler;

public class SigAbrt {

  private static volatile boolean abort = false;

  public static void main(String[] args) throws Exception {

    Signal.handle(new Signal("ABRT"), new SignalHandler () {
      public void handle(Signal sig) {
        System.out.println("got a SIGABRT");
        abort = true;
      }
    });

    for(int i=0; i<100; i++) {
      Thread.sleep(1000);
      System.out.print('.');
      if (abort) {
          System.out.println("ABORT");
          break;
      }
    }
  }
}

运行它
第一部分

java SigAbrt

第二课时

// first find the PID of SigAbrt
jps

第二课时的输出示例

2323  Jps
4242  SigAbrt

现在发送一个 SIGABRTSigAbrt 过程

kill -s SIGABRT 4242

会话1的输出示例

...........got a SIGABRT
.ABORT
fnatzsnv

fnatzsnv2#

程序无法在控制台上打印可能是因为 testfifo 文件为空。
试试这个:

printf "Hello\nMy\nFriend\nabort" > testfifo

java -cp "Test.jar" com.example.ProcessMain < testfifo

会有用的。

相关问题