Background process in java listening on stdin

I need to make a java program, when the user enters 0, he should exit. no problems with 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 start this process using start-stop script in linux. I can also do this using &ornohup

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 started this process, it read input -1. While I want to read from stdinput when somthing echoes it explicitly, that is, it calls. I just need a program that will be closed by the shell script explicitly. I tried very hard. Help me.

Edit:

, q . , , , . . Jnotify, , . , , SunOS.: (

+5
4

set -m script (, ), .

0

, fifo , .

read() . :

    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...
    }

, , 50 .

.

+3

Since you do not yet have data in the pipe, it read()sees the end of the stream, and because of this, it returns -1. Call available()before reading from the stream to make sure that there is information in it.

+1
source

When you execute a command in a script, the stdin of that command is implicitly redirected from /dev/null.

# test by executing a script with ...
- cat > myfifo & lsof -p $!
+ cat 0<&0 > myfifo & lsof -p $!
0
source

All Articles