0

I've to kill all running instances of Xvfb using shell script hence have following code -

for pid in $(ps -ef | awk '/Xvfb/ {print $2}'); do kill -9 $pid; done 

It kills all instances but one fails with following error -

kill: (142898) - No such process 

Seems above executed command creates one more instance but which no more exists while killing. In this case, how can I skip that and succeed with the script?

1
  • 2
    pkill Xvfb? Any reason to make it complicated? And why the SIGKILL? Commented Apr 9, 2020 at 9:56

2 Answers 2

0

The problem is that you are piping the output of ps into a call to awk that looks for the string "Xvfb" and therefore also contains the string "Xvfb" in its own command-line. Because both processes of a pipe are executed simultanously, the awk call itself will also register in the output of ps (try what happens if you just type ps -ef | awk '/Xvfb/' on the command-line).

However, by the time the loop is started (which happens when the command-substitution $( … ) and therefore the awk process, too, has exited), this awk process doesn't exist anymore, hence kill stumbles upon this.

You should be safe if you modify the command in the command substitution to

ps -ef | awk '$0 ~ /Xvfb/ && index($0,"awk")==0 {print $2}' 

which will ensure that no command containing the substring awk are included in the list.

0

You are attempting to kill the awk.

A simple regex trick to avoid this is to use some sort of escaping. Such as wor[d].

So for your code (with variable quoting added)

for pid in $(ps -ef | awk '/Xvf[b]/ {print $2}'); do kill -9 "$pid"; done 
1
  • 2
    Note that "$(...)" is a single string, so the loop is a bit useless. Commented Apr 9, 2020 at 9:57

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.