Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture the result of a system call in a shell variable?

We want to build a script that run every night (kills and restart a java process). For that we need to capture the process number (since there could be more than one java process running). The command below is basically what we will use to obtain the processes number, probably with a regexp at the end of the grep. Unless any better suggestions comes up.

root#ps -e |grep  'java'
18179 pts/0    00:00:43 java

We want to know how to parse the output above and get it into a shell variable so we can use the kill command as below.

kill -9 ${processid}
wait 10

Note1: The reason we cannot rely on the normal service stop command is because the processes sometimes does not want to die. And we have to use the kill command manually.

like image 985
Geo Avatar asked Apr 03 '09 16:04

Geo


2 Answers

There are a couple of options to solve this. If you're using bash, then the shell variable '$!' will contain the PID of the last forked-off child process. So, after you start your Java program, do something like:

echo $! > /var/run/my-process.pid

Then, after your init script stops the Java process:

# Get the pidfile.
pid=$(cat /var/run/my-process.pid)

# Wait ten seconds to stop our process.
for count in $(1 2 3 4 5 6 7 8 9 10); do
    sleep 1
    cat "/proc/$pid/cmdline" 2>/dev/null | grep -q java
    test $? -ne 0 && pid="" && break
done

# If we haven't stopped, kill the process.
if [ ! -z "$pid" ]; then
    echo "Not stopping; terminating with extreme prejudice."
    kill -9 $pid
fi

Make sure to remove the pidfile when you're done.

like image 125
Don Werve Avatar answered Oct 05 '22 02:10

Don Werve


ps aux | grep java | awk '{print $1}' | xargs kill -9

Here's an explanation:

ps aux gives you a listing of all processes

grep java gives you all of the processes whose names and command line arguments contain the string "java"

awk '{print $1}' parses the output of the grep command into columns by whitespace and re-prints only the first column

xargs kill -9 passes each of the results of the awk command as parameters to a kill -9 command

like image 37
Eli Courtwright Avatar answered Oct 05 '22 02:10

Eli Courtwright