need to check if the process is running

Hi,

I check if the process is running or not using the below.

 /usr/ucb/ps auxww | grep 10[9]9 |grep rmi |  awk '{print $2}'
9718

Thus we see 9718 is the PID.
It return blank if the process is not running.

I need to perform some action [start the process] if the process is not running and leave it if it is already running.

Can you please help me with the syntax?

Do you try "service --status-all" command?

Nopes I do not have root access and would want to stick to the grep i mentioned in my inaugural post.

Maybe something like this, give it a try:

#!/usr/bin/ksh
/usr/ucb/ps auxww | grep 10[9]9 |grep rmi 

if [ $? -eq 0 ]
then
pid = `/usr/ucb/ps auxww | grep 10[9]9 |grep rmi| awk '{print $2}'`
echo "process $pid running, doing nothing..."
else
echo "not running..starting process"
<put the command to start process>
fi
1 Like

You don't mention what OS you are running, so here's a start:

#!/bin/bash
PIDS=$(ps auxww | awk '/(10[9]9)/ || /(rmi)/ {print $2}')
for pid in $PIDS; do
	# Whatever you need to do to start your process.
done

Why so ?

/usr/ucb/ps auxww | grep onli[n]e0331 | grep rmi
echo $?
1
/usr/ucb/ps auxww | grep onli[n]e0331 | grep rmi | awk '{print $2}'
echo $?
0

I am expecting both of them to return 1 as the process is "Not" running.

Can anyone explain?

awk doesn't know that anything's wrong, and you only get the return value of the last command.

It's traditional to have whatever runs a persistent program save its PID in a file, so you don't need to resort to ps | grep | awk | kitchen | sink tricks to find out what the PID is. This also allows systems where more than one instance of it can be run independently without interfering with each other.

ok.
return value of the last command was 1

/usr/ucb/ps auxww | grep onli[n]e0331 | grep rmi
echo $?
1

but

/usr/ucb/ps auxww | grep onli[n]e0331 | grep rmi | awk '{print $2}'
echo $?
0

I guess by your statement its should return the last value which is 1 in my case.

We do not have root access so i am not sure how can I get the PID if not using the ps command. Kindly help if you know an more professional way of achieving this.

What makes you think 1 was the last value? It's the last value that you care about, but it's not the last value, the last one is the one returned by awk. How's it to know anything's wrong if nobody tells it so?

$ echo asdf | awk '{}'
$ echo $?
0
$ awk '{}' < /dev/null
$ echo $?
0

That depends. How do you run the command in the first place?

In the shell you can run something in the background and save its PID like

./program &
echo $! > pidfile