I try to start a java programm and a echo command at once in my shell script, first I tried this
java -jar server.jar & echo "$!" > $pidfile
but this stopps the server.jar
when the echo finishes, I solved this with
java -jar server.jar & echo "$!" > $pidfile && fg
It works for me but I think this isn't a clean solution.
Now I need to add another java program, and both programs should run at the same time, and the script should end if both programs are finished/stopped. I read in another StackOverflow question that I should add a & wait
at the end of the line, but this will stop my server.jar
.
Actually it looks like this:
java -jar server.jar & echo "$!" > $pidfile && fg && java -jar heartbeat.jar
Edit: The whole script and server are running in tmux, so it's not necessary to keep it alive. The server.jar
is running around 24h and the heartbeat.jar
check if the server is alive, both should started with one script.
Solution:
java -jar server.jar & echo "$!" > $pidfile ; java -jar heartbeat.jar & fg %1
I recieve both outputs from the jars
, input command went to server.jar
There is a program called daemon which does put your program in background and saves pid in the file.
Also there is program that starts multiple programs at the same time called foreman , which is great for development purposes. Its written in ruby, but there are alternatives in other languages. Java implementation gaffer .
Just to explain: The reason for your Java program stopping is that all background processes will receive a HUP
signal when the shell executing your script terminates. To prevent this, you can remove it from the list of the shell's jobs using disown
right after the &
.
For the two Java programs, I would suggest:
java -jar server.jar & # start java with server.jar as a background job
echo "$!" > "$pidfile" # echo the pid of the last background job into the pid file
java -jar heartbeat.jar & # start java with heartbeat.jar as a background job
fg %1 # set server.jar as foreground job for interactive use
Edit: wait
replaced with fg %1
, see comments.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.