run & kill a Bash command from Java - java

I'm running arbitrary bash commands on Linux from a Java program using a ProcessBuilder:
ProcessBuilder pb = new ProcessBuilder("setsid", "/bin/bash", "-c", command);
process = pb.start();
The commands run fine, but when I try to kill them with process.destroy() they keep running. What's the best way to kill the command?

Write a bash script and run it from Java:
For running a program from Java by bash:
run.sh
#!/bin/bash
firefox # replace firefox by the program you like to start
For killing by program name:
kill.sh
#!/bin/bash
pkill -9 -x firefox # replace firefox by the program you like to kill
For killing the program by PID:
kill.sh
#!/bin/bash
kill -9 $PID
You can get the PID of program by start of program on follow way by bash:
firefox & $! # start the program and get the pid
echo $! # echo the pid of program
You can get the PID of a already running program by his name by bash:
pidof -x firefox
4561 # thats a sample of a output of a pid

Related

War file automated deployment

So I deploy war files on a Linux box using java automatically
and the same commands are always used
ps -ef | grep java
kill - 9 (java process)
java -jar ROOT.war &>/dev/null &
However, I get different versions for it so like
ROOT_1.0.2.war
ROOT_1.0.3.war
ROOT_1.0.4.war
ROOT_1.0.5.war
I want the script to see the new .war and deploy it automatically
and keep it deployed which is why I use &>/dev/null & so it runs in the till it is killed again till the new version is put in that directory
echo Enter the name of the process you want to kill eg ROOT.war?
enter code here
read process
##Kill selected process
file="$process"
if [ -f "$file" ];
then
pkill -9 -f $process
echo process stopped >> satrixWar.txt
sleep 3s
## Start Up selected process
echo Enter the name of the process you want to start
read process2
java -jar $process2 &>/dev/null &
echo process starting up>> satrixWar.txt
else
echo "Process $process does not exist" >&2
fi
##Confirm new proess is up
echo What is currently installed >> satrixWar.txt
ps -ef | grep $process2 >> satrixWar.txt
mail -a text file path -s "name"
"email.com" < /dev/null
rm -rf War.txt

Unable to run nohup command from jenkins as a background process

UPDATE: Based on below discussion I have edited my answer for more accurate description.
I am trying to run a nohup command from jenkins. The full command is
nohup java -jar /home/.../jar/server-process-0.35.jar prod >> /var/../server-process-prod.log 2>&1 &
This command does not work. I can see status as success in jenkins but no java process in linux. When I do 'ps -ef | grep java'
However when I remove the last '&' , that is I change it from run in forground instead of background
It starts working. I can see the java process started.
The original command works fine If I run it on linux console.
I need to run it from jenkins in the original form that is as a backgorund process. So that it is independant of jenkins.
Any clues why is this happening?
Long story short, Jenkins kills all processes spawned by a job once that job finishes. To override this behavior, you need to set an environment variable.
The variable appears to vary from job type to job type. It used to be BUILD_ID, but for Pipeline jobs it is JENKINS_NODE_COOKIE, and there are several others mentioned in this answer.
So if you're running your command in Pipeline, it would look like this:
sh 'JENKINS_NODE_COOKIE=dontKillMe nohup java -jar /home/.../jar/server-process-0.35.jar prod >> /var/../server-process-prod.log 2>&1 &'
See the wiki on ProcessTreeKiller and this comment in the Jenkins Jira for more information.
In your jenkins shell script try:
export BUILD_ID=dontKillMe
nohup java -jar your_java_app.jar &
It worked for me!
I tried every possible combination with BUILD_ID but it didn't work.
I made it though by putting "nohup command > output.txt&" inside a shell script ran by the execute shell in jenkins, it worked perfectly!
Got the same problem, added:
BUILD_ID=dontKillMe python /var/lib/jenkins/release.py
into Execute Shell -> Command and inside release.py there is:
os.system('nohup java -jar ' + new_jars_on_server + '/' + generated_jar_by_mvn_name + '&')
and it works
Best simple solution is to use "at now" instead of "nohup"
In your job jenkins (execute shell) put :
set +e #so "at now" will run even if java -jar fails
#Run java app in background
echo "java -jar $(ls | grep *.jar | head -n 1)" | at now + 1 min
what worked for me was wrapping the nohup java -jar ... command into sh file inside execute shell command, and running that same sh file right after:
echo "starting java jar..."
cd [some location where jar is]
echo "nohup java -jar [jar_name].jar &" > start-jar-in-background.sh
sh start-jar-in-background.sh
echo "started java jar"
If I had nohup java -jar ... inline with Execute shell command, then it didn't start it from some reasons. I spent quite some time on this, hope it helps to someone ';)
Simplest way :
`nohup java -jar [jar_name].jar >log_file_you_want 2>another_file`&
set +e #so "at now" will run even if java -jar fails
#Run java app in background
echo "java -jar $(ls | grep *.jar | head -n 1)" | at now + 1 min
above command worked for him, thanks #walid, & remove at the end (+ 1 min)

Running Scrapy from bash (shell script)

I have developed a web app in Java which uses Scrapy to get some data. To reach that, I invoke a shell script from Java:
Process p = Runtime.getRuntime().exec("sh myPath/myScript.sh");
p.waitFor();
which contains
#!/bin/bash
cd mySpiderPath
echo "We are going tu run scrapy"
scrapy crawl mySpider
echo "done!"
After running it, both "echo" are printed but scrapy does nothing. If I run myScript.sh from shell it works perfectly... I'm confused!
What can I do to try to debug this strange behavior?
EDIT
I have changed myScript.sh to run python version instead of scrapy command, and it doesn't work... so, the conclusion is that is not an "scrapy problem" but it is a bash script problem when it's invoked from Java...any ideas? (if I execute myScript.sh from shell it works fine)
#!/bin/bash
cd mySpiderPath
echo "We are going tu run scrapy"
python --version
echo "done!"
Try changing:
Process p = Runtime.getRuntime().exec("sh myPath/myScript.sh");
to:
Process p = Runtime.getRuntime().exec("bash myPath/myScript.sh");
This will probably run the script with /bin/bash instead of /bin/sh, that often points to a simpler shell.

How to restart a Jar file on init.d?

I am using CentOS 6.3 64bit.
I am using starting my server as a service.
#!/bin/sh
# chkconfig: 2345 90 10
#description: URL Server
# processname: urlovedserver
start(){
java -jar /root/BookkServer-0.0.1-jar-with-dependencies.jar
}
# See how we were called.
case "$1" in
start)
start
;;
*)
echo "Usage: $0 {start}"
exit 1
esac
What should I add to the script so that it responds to "service urlovedserver restart"? I can't get how to stop a java service.
Write PID in file. When you want you can read PID-file for kill java process.
start(){
#run your process in background
java -jar /root/BookkServer-0.0.1-jar-with-dependencies.jar &
# write PID
echo $! > program.pid
}
Now you can kill process:
kill -9 `cat program.pid` #kill java process
One idea would be to get the pid of the executed command (use the $! shell variable) save it in a file and then add a stop command in your shell script that just kills the java process that it reads from the previous file. Something like
kill -9 `cat /var/run/myjavaservice.pid`.
Then restart will be just stop() and start()

difference between running shell command directly and from shell script sh file

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 Java side, but instead on the fact that your shell handles differently the job control when launching a script. From man bash:
JOB CONTROL
Job control refers to the ability to selectively stop (suspend) the
execution of processes and continue (resume) their execution at a later
point. A user typically employs this facility via an interactive
interface supplied jointly by the operating system kernel's terminal
driver and 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 (with fg). When launched in a script, instead, job control is disabled so, as soon as cat tries to read from the (detached) terminal, it exists, closing the pipe (and your Java process reads EOF).
If you use set -m at the top of your shell script (hence enabling forcefully job control), you should see a consistent behavior.
set [+abefhkmnptuvxBCEHPT] [+o option-name] [arg ...]
-m Monitor mode. Job control is enabled. This option is on by
default for interactive shells on systems that support it
(see JOB CONTROL above). Background processes run in a sep‐
arate process group and a line containing their exit status
is printed upon their completion.

Categories