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

We want to create a script that runs every night (kills and restarts the Java process). To do this, we need to fix the process number (since more than one java process can work). The command below is mainly used to get process numbers, possibly with a regular expression at the end of grep. If no suggestions appear.

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

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

kill -9 ${processid}
wait 10

Note1: The reason we cannot rely on the usual service shutdown command is because processes sometimes do not want to die. And we must use the kill command manually.

+5
source share
7 answers

There are several solutions to this problem. If you use bash, then the shell variable $! will contain the PID of the last forked child process. So, after starting your Java program, do something like:

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

Then after the 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

Be sure to remove the pidfile when done.

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

Here is an explanation:

ps aux gives you a list of all processes

grep java provides you with all processes whose command line names and arguments contain the string "java"

awk '{print $1}' parses grep output into columns by spaces and reprints only the first column

xargs kill -9 awk kill -9

+3

, , :

pidof java | xargs kill
+2

PID PID , ( awk, ), PID:

[user@host ~]$ ps -e | grep java | cut -d' ' -f1
12812
12870
13008
13042
13060

Java, , , . , :

JAVA_PROCS=`ps -e | grep java | cut -d' ' -f1`

, :

for proc in $JAVA_PROCS; do
    kill -9 $proc; 
done

, , , :

kill -9 $JAVA_PROCS
+1

, , grep ( grep java, ). , grep ( grep!):

pid=`ps -e | fgrep java | fgrep -v grep | awk '{print $1}'`
# check pid has a value
# kill $pid

ps -e -opid,args.

A better alternative is to use pgrep(1)or pkill(1)if your system has them. More pipes, saddles, awks, cuts, xargs:

pkill -9 java
+1
source

killing him:

ps -e | grep java | cut -f1 -d' ' | xargs kill -9

saving PID for a variable:

export JAVAPID=`ps -e | grep 'java' | cut -f1 -d' '`

verify that this worked:

echo $JAVAPID
0
source

I am using something like this:

kill $(ps -A | grep java | cut -b 1-5)
0
source

All Articles