I have a java program in which I am reading from stdin
BufferedInputStream bis = new BufferedInputStream(System.in);
byte[] b = new byte[1];
int cmd = bis.read(b);
System.out.println("Read command: " + new String(b));
And a shell script to start-stop this program
'start')
if [ -p myfifo ]; then
rm myfifo
rm myfifo-cat-pid
fi
mkfifo myfifo
cat > myfifo &
echo $! > myfifo-cat-pid
java -jar lib/myJar.jar >/dev/null 2>&1 0<myfifo &
echo `date +%D-%T` $! >> process.pid
echo "Started process: "$!
;;
'stop')
echo 0 > myfifo
echo "Stopped process: "
rm myfifo
;;
When I run commands in start one by one the program waits until i echo on fifo. But when I run it from .sh file it immediately reads from stdin. Dont understand what is the difference between if run a command directly on command prompt and if I make a .sh file and run it then
The difference is not on the
Javaside, but instead on the fact that your shell handles differently the job control when launching a script. Fromman bash:As explained here, by default job control is disabled in a script.
When
cat > myfifo &is executed in an interactive shell, it remains in “Stopped” mode waiting to be put in foreground again (withfg). When launched in a script, instead, job control is disabled so, as soon ascattries to read from the (detached) terminal, it exists, closing the pipe (and yourJavaprocess readsEOF).If you use
set -mat the top of your shell script (hence enabling forcefully job control), you should see a consistent behavior.