Check and run/restart processes, bash [duplicate] - java

This question already has answers here:
Linux Script to check if process is running and act on the result
(8 answers)
Closed 5 years ago.
I wrote a bash-script to check if a process is running. It doesn't work since the ps command always returns exit code 1. When I run the ps command from the command-line, the $? is correctly set, but within the script it is always 1. Any idea?
#!/bin/bash
SERVICE=$1
ps -a | grep -v grep | grep $1 > /dev/null
result=$?
echo "exit code: ${result}"
if [ "${result}" -eq "0" ] ; then
echo "`date`: $SERVICE service running, everything is fine"
else
echo "`date`: $SERVICE is not running"
fi
Bash version: GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)

There are a few really simple methods:
pgrep procname && echo Running
pgrep procname || echo Not running
killall -q -0 procname && echo Running
pidof procname && echo Running

This trick works for me. Hope this could help you. Let's save the followings as checkRunningProcess.sh
#!/bin/bash
ps_out=`ps -ef | grep $1 | grep -v 'grep' | grep -v $0`
result=$(echo $ps_out | grep "$1")
if [[ "$result" != "" ]];then
echo "Running"
else
echo "Not Running"
fi
Make the checkRunningProcess.sh executable.And then use it.
Example to use.
20:10 $ checkRunningProcess.sh proxy.py
Running
20:12 $ checkRunningProcess.sh abcdef
Not Running

I tried your version on BASH version 3.2.29, worked fine. However, you could do something like the above suggested, an example here:
#!/bin/sh
SERVICE="$1"
RESULT=`ps -ef | grep $1 | grep -v 'grep' | grep -v $0`
result=$(echo $ps_out | grep "$1")
if [[ "$result" != "" ]];then
echo "Running"
else
echo "Not Running"
fi

I use this one to check every 10 seconds process is running and start if not and allows multiple arguments:
#!/bin/sh
PROCESS="$1"
PROCANDARGS=$*
while :
do
RESULT=`pgrep ${PROCESS}`
if [ "${RESULT:-null}" = null ]; then
echo "${PROCESS} not running, starting "$PROCANDARGS
$PROCANDARGS &
else
echo "running"
fi
sleep 10
done

Check if your scripts name doesn't contain $SERVICE. If it does, it will be shown in ps results, causing script to always think that service is running. You can grep it against current filename like this:
#!/bin/sh
SERVICE=$1
if ps ax | grep -v grep | grep -v $0 | grep $SERVICE > /dev/null
then
echo "$SERVICE service running, everything is fine"
else
echo "$SERVICE is not running"
fi

Working one.
!/bin/bash
CHECK=$0
SERVICE=$1
DATE=`date`
OUTPUT=$(ps aux | grep -v grep | grep -v $CHECK |grep $1)
echo $OUTPUT
if [ "${#OUTPUT}" -gt 0 ] ;
then echo "$DATE: $SERVICE service running, everything is fine"
else echo "$DATE: $SERVICE is not running"
fi

Despite some success with the /dev/null approach in bash. When I pushed the solution to cron it failed. Checking the size of a returned command worked perfectly though. The ampersrand allows bash to exit.
#!/bin/bash
SERVICE=/path/to/my/service
result=$(ps ax|grep -v grep|grep $SERVICE)
echo ${#result}
if ${#result}> 0
then
echo " Working!"
else
echo "Not Working.....Restarting"
/usr/bin/xvfb-run -a /opt/python27/bin/python2.7 SERVICE &
fi

#!/bin/bash
ps axho comm| grep $1 > /dev/null
result=$?
echo "exit code: ${result}"
if [ "${result}" -eq "0" ] ; then
echo "`date`: $SERVICE service running, everything is fine"
else
echo "`date`: $SERVICE is not running"
/etc/init.d/$1 restart
fi
Something like this

Those are helpful hints. I just needed to know if a service was running when I started the script, so I could leave the service in the same state when I left. I ended up using this:
HTTPDSERVICE=$(ps -A | grep httpd | head -1)
[ -z "$HTTPDSERVICE" ] && echo "No apache service running."

I found the problem. ps -ae instead ps -a works.
I guess it has to do with my rights in the shared hosting environment. There's apparently a difference between executing "ps -a" from the command line and executing it from within a bash-script.

A simple script version of one of Andor's above suggestions:
!/bin/bash
pgrep $1 && echo Running
If the above script is called test.sh then, in order to test, type:
test.sh NameOfProcessToCheck
e.g.
test.sh php

I was wondering if it would be a good idea to have progressive attempts at a process, so you pass this func a process name func_terminate_process "firefox" and it tires things more nicely first, then moves on to kill.
# -- NICE: try to use killall to stop process(s)
killall ${1} > /dev/null 2>&1 ;sleep 10
# -- if we do not see the process, just end the function
pgrep ${1} > /dev/null 2>&1 || return
# -- UGLY: Step trough every pid and use kill -9 on them individually
for PID in $(pidof ${1}) ;do
echo "Terminating Process: [${1}], PID [${PID}]"
kill -9 ${PID} ;sleep 10
# -- NASTY: If kill -9 fails, try SIGTERM on PID
if ps -p ${PID} > /dev/null ;then
echo "${PID} is still running, forcefully terminating with SIGTERM"
kill -SIGTERM ${PID} ;sleep 10
fi
done
# -- If after all that, we still see the process, report that to the screen.
pgrep ${1} > /dev/null 2>&1 && echo "Error, unable to terminate all or any of [${1}]" || echo "Terminate process [${1}] : SUCCESSFUL"

I need to do this from time to time and end up hacking the command line until it works.
For example, here I want to see if I have any SSH connections, (the 8th column returned by "ps" is the running "path-to-procname" and is filtered by "awk":
ps | awk -e '{ print $8 }' | grep ssh | sed -e 's/.*\///g'
Then I put it in a shell-script, ("eval"-ing the command line inside of backticks), like this:
#!/bin/bash
VNC_STRING=`ps | awk -e '{ print $8 }' | grep vnc | sed -e 's/.*\///g'`
if [ ! -z "$VNC_STRING" ]; then
echo "The VNC STRING is not empty, therefore your process is running."
fi
The "sed" part trims the path to the exact token and might not be necessary for your needs.
Here's my example I used to get your answer. I wrote it to automatically create 2 SSH tunnels and launch a VNC client for each.
I run it from my Cygwin shell to do admin to my backend from my windows workstation, so I can jump to UNIX/LINUX-land with one command, (this also assumes the client rsa keys have already been "ssh-copy-id"-ed and are known to the remote host).
It's idempotent in that each proc/command only fires when their $VAR eval's to an empty string.
It appends " | wc -l" to store the number of running procs that match, (i.e., number of lines found), instead of proc-name for each $VAR to suit my needs. I keep the "echo" statements so I can re-run and diagnose the state of both connections.
#!/bin/bash
SSH_COUNT=`eval ps | awk -e '{ print $8 }' | grep ssh | sed -e 's/.*\///g' | wc -l`
VNC_COUNT=`eval ps | awk -e '{ print $8 }' | grep vnc | sed -e 's/.*\///g' | wc -l`
if [ $SSH_COUNT = "2" ]; then
echo "There are already 2 SSH tunnels."
elif [ $SSH_COUNT = "1" ]; then
echo "There is only 1 SSH tunnel."
elif [ $SSH_COUNT = "0" ]; then
echo "connecting 2 SSH tunnels."
ssh -L 5901:localhost:5901 -f -l USER1 HOST1 sleep 10;
ssh -L 5904:localhost:5904 -f -l USER2 HOST2 sleep 10;
fi
if [ $VNC_COUNT = "2" ]; then
echo "There are already 2 VNC sessions."
elif [ $VNC_COUNT = "1" ]; then
echo "There is only 1 VNC session."
elif [ $VNC_COUNT = "0" ]; then
echo "launching 2 vnc sessions."
vncviewer.exe localhost:1 &
vncviewer.exe localhost:4 &
fi
This is very perl-like to me and possibly more unix utils than true shell scripting. I know there are lots of "MAGIC" numbers and cheezy hard-coded values but it works, (I think I'm also in poor taste for using so much UPPERCASE too). Flexibility can be added with some cmd-line args to make this more versatile but I wanted to share what worked for me. Please improve and share. Cheers.

A solution with service and awk that takes in a comma-delimited list of service names.
First it's probably a good bet you'll need root privileges to do what you want. If you don't need to check then you can remove that part.
#!/usr/bin/env bash
# First parameter is a comma-delimited string of service names i.e. service1,service2,service3
SERVICES=$1
ALL_SERVICES_STARTED=true
if [ $EUID -ne 0 ]; then
if [ "$(id -u)" != "0" ]; then
echo "root privileges are required" 1>&2
exit 1
fi
exit 1
fi
for service in ${SERVICES//,/ }
do
STATUS=$(service ${service} status | awk '{print $2}')
if [ "${STATUS}" != "started" ]; then
echo "${service} not started"
ALL_SERVICES_STARTED=false
fi
done
if ${ALL_SERVICES_STARTED} ; then
echo "All services started"
exit 0
else
echo "Check Failed"
exit 1
fi

The most simple check by process name :
bash -c 'checkproc ssh.exe ; while [ $? -eq 0 ] ; do echo "proc running";sleep 10; checkproc ssh.exe; done'

Related

How can I stop all processes in IntelliJ?

I am using intelliJ IDEA.
When I run my programs and close the window, the process still remains. If I run a lot of programs, I need to click disconnect many times.
Is there any way to stop all processes?
Eclipse doesn't have this problem.
IntelliJ 2017.2 now has a "Stop All" button in the "Stop process" menu (the button on the top bar), with the default shortcut ⌘+F2 on Mac OS:
For older versions:
Click the Stop button from the top bar. It will pop open a menu listing all processes. (The stop button at the side of the debug window is per-process, as in your screenshot.)
Hover over the first process, hold Shift, and then click on the last process.
Press Enter.
Screenshot showing the result of steps 1 & 2:
kill $(ps aux | grep 'java' | awk '{print $2}')
This is a nice little workaround I found on SO a while ago that will kill any process with "java" in the name.
Just copy and paste into the terminal.
Not exactly perfect, but what you could do is press Ctrl + F2 (shortcut for Stop Process) and hit Enter. It's better than all that mouse clicking and gets you through a list of running processes quite fast.
You can create a script like killJavaProcess and invoke it in Before launch section as External tool
For example ~/.bin/killonport
#!/bin/zsh
function help() {
echo "usage: killonport port"
echo "-f don't ask before killing"
echo "-h help"
}
function killListenerOnPort() {
# get script options
zparseopts -E -D h=HELP f=FORCE
[[ -n $HELP ]] &&
help &&
return
local PORT
PORT=$1
[[ -z "$PORT" ]] &&
help &&
return
local LISTEN
# find process listening on port with lsof
LISTEN="$(lsof -nP -iTCP:"$PORT" -sTCP:LISTEN)"
local PROCESS
# remove first line of output lsof
PROCESS="$(echo "$LISTEN" | tail -n +2)"
local HEAD
# get first line of output lsof
HEAD="$(echo "$LISTEN" | head -n 1)"
[[ -z $PROCESS ]] &&
echo "Process not found" &&
return
local COUNT
# assure that found only one process else printing founded processes and exit
COUNT=$(echo "$PROCESS" | wc -l | xargs)
[[ $COUNT -gt 1 ]] &&
printf 'Found more then one process: %s\n%s\n%s\n' "$COUNT" "$HEAD" "$PROCESS" &&
return
# get name and PID
local NAME
NAME=$(echo "$PROCESS" | awk '{print $1}')
local PID
PID=$(echo "$PROCESS" | awk '{print $2}')
# if -f option specified kill silently
[[ -n "$FORCE" ]] &&
kill -9 "$PID" &&
return
# ask confirmation to kill
echo "Kill process '$NAME' with PID '$PID'"
read -qr 'REPL?Continue? (y/n) '
echo
# kill if confirmed
[[ $REPL == 'y' || $REPL == 'Y' ]] &&
kill -9 "$PID"
}
killListenerOnPort "$#"

How do I write a shell script to get a given process idle time?

I am new to Linux. I don't know about shell scripts. I need to get the idle process time of a given Linux process. I am writing a Java program. But there are no Linux commands for my need. How do I write a shell script that could do this? Then I can execute this script from Java.
Here you are:
#! /bin/bash
# Assumptions:
# Process is attached to a tty.
#
[[ -z "$1" ]] && echo "Usage: $0 pid" && exit 1
[[ "$1" != +([0-9]) ]] && echo "$1 is not a valid pid" && exit 1
PID="$1"
W=$(which w)
PS=$(which ps)
SED=$(which sed)
AWK=$(which awk)
TTY=$($PS -o tty4 $PID)
TTNo=$(echo "$TTY" | $SED -e '/TTY/d')
TIME=$($W | $SED -n -e "/pts\/$TTNo/p" | $AWK '{ print $5 }')
echo $PID has been idle for $TIME

Check if jar running from shell

I have a java jar program that I am trying to run on startup of my machine. Ideally, the shells script will check every 60 seconds to assure that the jar is running. How do I check if the jar is running on centos, this does not appear to be working?
My current .sh file:
#!/bin/bash
while [ true ]
do
cnt=`ps -eaflc --sort stime | grep /home/Portal.jar |grep -v grep | wc -l`
if(test $cnt -eq 3);
then
echo "Service already running..."
else
echo "Starting Service"
java -jar /home/Portal.jar >> /dev/null &
fi
sleep 1m
done
I used this for referencing so far.
Depending on what your program does, there may be more or less intelligent ways to check it. For example, if you have some server, it will listen on a port.
Then something like
netstat -an | fgrep tcp | fgrep LISTEN | fgrep :87654 # or whatever your port is
could do the job.
Then there is lsof, which could also detect listening ports.
Finally, you could connect and issue a pseudo request. For example, for a http server, you could use lynx or curl. For a server with a non-stamdard protocol, you can write a small client program whose sole purpose is to connect to the server just to see if it is there.
Store your process id in file and check for this process.
#!/bin/bash
while [ true ]
do
pid=$(cat /tmp/portal.pid)
if [[ -n "$pid" && $(ps -p $pid | wc -l) -eq 2 ]]
then
echo "Service already running..."
else
echo "Starting Service"
java -jar /home/Portal.jar >> /dev/null &
echo $! > /tmp/portal.pid
fi
sleep 1m
done
/tmp will be cleared on restart, all right in this case.
I did the very same scenario a couple of months ago. My task was to ensure a jar distributed java program to run 24/7 on a Linux server.
My program was console-based, started, did something then stopped.
I did a shell script that started, waited to end and then re-started the app in an infinite loop.
I installed runit, created a service and supplied this script as the run script. Works very well.
In general, the shell script ensures that the java program is running and runit ensures that the start script (which is our script) is running.
You find valuable info here: http://smarden.org/runit/faq.html
Rather than putting the process to sleep , I'd rather have it exit and use crontab to run the process every 1 min;which will check if its running or else just stop the script.
#!/bin/sh
declare -a devId=( "/Path/To/TestJar.jar Test1" "/Path/To/TestJar.jar Test2" ) #jarfile with pathname and Test as argument
# get length of an array
arraylength=${#devId[#]}
# use for loop to read all values and indexes
for (( i=1; i<${arraylength}+1; i++ ));
do
y=${devId[$i-1]}
cnt=`ps -eaflc --sort stime | grep "$y" |grep -v grep | wc -l`
if [ $cnt = 0 ]
then
java -jar $y& > /dev/null
b=$(basename $y)
echo $b
#DO SOME OPERATION LIKE SEND AN EMAIL OR ADD TO LOG FILE
continue
elif [ $cnt != 0 ]
then
echo 'do nothing'
fi
done
Why do you think $cnt should be equal to 3? Shouldn't it be equal to 1 if the process is already running?
You could use the jps command. It return the JVMs running in the system.
I created following script to monitor my application jar is running or not.
In this case My application jar is running on port 8080
#!/bin/bash
check=$(netstat -an | grep 8080 | wc -l)
if [[ $check -eq 0 ]];then
echo "jar is not running..."
/usr/bin/java -jar /path/to/target/application.jar >> /dev/null &
else
echo "it is running"
fi
I am using cronjob to monitor jar app by executing shell script on every minute.
$ crontab -e
in the end of file
* * * * * /bin/bash monitor-jar.sh /dev/null 2>&1

Check Process using Shell Script

I am developing a Java program which checks the running processes, if not start that process. In my context I am executing the .sh file which is like this.
#!/bin/sh
echo "Hello World..."
cnt=`ps -eaflc --sort stime | grep clientApplication.jar | grep -v grep | wc -l`
if [ $cnt = 3 ]
then
echo "Services for Pigeon are already running..."
else
echo "Starting Services for Pigeon..."
echo `java -jar clientApplication.jar`
fi
But it's not working. What's the problem?
Using the test expression works. Hope this helps !!
echo "Hello World"
cnt=`ps -eaflc --sort stime | grep clientApplication.jar |grep -v grep | wc -l`
if(test $cnt -eq 3) ;
then
echo "Services for Pigeon are already running..."
else
echo "Starting Services for Pigeon..."
echo `java -jar clientApplication.jar`
fi
I am not sure. Try this
cnt=$(`ps -eaflc --sort stime | grep clientApplication.jar | grep -v grep | wc -l`)
if[$cnt -eq 3]; then
Just try this
echo won't execute anything it will just print the content what is there in double quotes.
So if i have understood your requirement you should be doing this instead of
echo "Hello World"
cnt=ps -eaflc --sort stime | grep clientApplication.jar |grep -v grep | wc -l
if(test $cnt -eq 3) ;
then
echo "Services for Pigeon are already running..."
else
echo "Starting Services for Pigeon..."
/bin/java -jar clientApplication.jar
fi
Hope this will work, i haven't tested it now
Equality checks should be ==, = is assignment
I'd use $(expr) rather than `expr`
if(expr) not if[expr]
not sure if you intend to echo the java line or not, it's not going to start the jar by telling it to print. I got rid of the echo since you said you wanted to start it.
so if you try this, it will work:
#!/bin/sh
echo "Hello World..."
cnt=$(ps -eaflc --sort stime | grep clientApplication.jar | grep -v grep | wc -l)
if($cnt==3)
then
echo "Services for Pigeon are already running..."
else
echo "Starting Services for Pigeon..."
java -jar clientApplication.jar
fi

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.
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.
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
I realize this is old, but what about:
pidof java | xargs kill
You can easily get the PID or list of PIDs into a variable using backticks and cut (or awk if preferred) to retrieve only the PID field:
[user#host ~]$ ps -e | grep java | cut -d' ' -f1
12812
12870
13008
13042
13060
Note in the above example I have multiple Java processes running hence the multiple values. If you save this into a variable like so:
JAVA_PROCS=`ps -e | grep java | cut -d' ' -f1`
You can iterate through the processes to kill them if desired:
for proc in $JAVA_PROCS; do
kill -9 $proc;
done
Of course, if you're only retrieving one process, then there's no need to iterate and you can just run it as:
kill -9 $JAVA_PROCS
If you do what you suggest, you may end up capturing the grep itself and killing that (since your grep command contains the java string that you are searching for). You can work around this by excluding grep (by using another grep!):
pid=`ps -e | fgrep java | fgrep -v grep | awk '{print $1}'`
# check pid has a value
# kill $pid
You might also like ps -e -opid,args.
A better alternative is to use pgrep(1) or pkill(1) if your system has them. No more pipes, seds, awks, cuts, xargs:
pkill -9 java
I use something like this:
kill $(ps -A | grep java | cut -b 1-5)
killing it:
ps -e | grep java | cut -f1 -d' ' | xargs kill -9
storing PID on variable:
export JAVAPID=`ps -e | grep 'java' | cut -f1 -d' '`
checking that it worked:
echo $JAVAPID

Categories

Resources