Search code examples
javashellstdinbackground-process

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. :(


Solution

  • If you use set -m at the top of your shell script (hence enabling forcefully job control), you should see a consistent behavior.