Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

background process in java listening to stdin

I have to make a java program that when user enters 0 it should exit. no problem writing in java code.

int cmd = read();
System.out.println("got command : " + cmd);
if (cmd == 48) { // ASCII code for 0
System.exit(0);

I want to run this process using start-stop script in linux. I am also being able to do that using & or nohup

case "$1" in    
  'start')
    if [ -f myfifo ]; then
      rm myfifo
    fi
    mkfifo myfifo
    cat > myfifo &
    echo $! > myfifo-cat-pid
    java -jar myjar.jar >/dev/null 2>&1 0<myfifo &
    echo "Started process: "$!
    ;;

  'stop')
    echo 0 > myfifo
    echo "Stopped process: "
    rm myfifo
    ;;
esac

My problem is as soon as i run this process it read input -1. While I want to read from stdinput when somthing is echoed to it explicitly i.e. stop is called. Simply i need a program to be closed by shell script explicitly. I have tried hard. Help me.

Edit :

I just want to close the program when user press q or any such event and dont want infinite loop in code. Any other approach like listening to other events will also help if possible. My code should not be polling for event. I have tried Jnotify which watch a directory and rise an event when file is created or deleted in that directory. But hard luck they dont have support for SunOS. :(

like image 480
Abhishek bhutra Avatar asked Oct 07 '22 03:10

Abhishek bhutra


1 Answers

Well, in fact the fifo files seems not behave exactly as you imagine.

The read() command is not blocking on a pipe. You should loop until you get data:

    try {
        bis = new BufferedInputStream(System.in);
        while (true) {
            byte[] buffer = new byte[4096];
            if (bis.available() > 0) {
                bis.read(buffer, 0, bis.available());
                // do some clever thing
            } else {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (IOException e) {
        // it failed...
    }

This will try to read and if there is nothing, then it will wait for 50 ms.

M.

like image 54
poussma Avatar answered Oct 12 '22 22:10

poussma