Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminating infinite loop with piped command in scope

Tags:

bash

unix

I have a very simple unix bash script I am using to execute a command every second. It has the following form:

while : ; do
  cat /proc/`pidof iBrowser.bin`/smaps | awk -f ./myawkscript.awk >> $DIRPATH
  sleep 1
done

The script runs fine, but it won't stop! If I hit ctrl-C while the script is running, the process does not stop, and I get the following error:

cat: can't open '/proc//smaps': No such file or directory

Does anyone know how this can be avoided?

like image 353
MM. Avatar asked Mar 10 '26 13:03

MM.


2 Answers

You should consider a trap function. See this and this.

To trap ctrl-c, you'd define a handler, eg:

ctrl_c ()
{
    # Handler for Control + C Trap
    echo ""
    echo "Control + C Caught..."
    exit
}

And then state that you wish to trap it with that handler:

trap ctrl_c SIGINT

Alternatively...

you could run the script in the background by appending &, e.g.

$ ./your_script.sh &

Which would present you with a job id in [square brackets]:

$ ./your_script.sh &
[1] 5183

(in this case 1). When you were done, you could terminate the process with

$ kill %1

Note the percent sign indicates you are referencing a job and not a process id

like image 92
jedwards Avatar answered Mar 13 '26 10:03

jedwards


awk -f ./myawkscript.awk /proc/`pidof iBrowser.bin`/smaps >> $DIRPATH \
  || exit 1

will exit the script if the awk invocation fails, which happens when pidof fails due to an erroneous path. I've taking the liberty of removing your UUOC.

like image 44
Fred Foo Avatar answered Mar 13 '26 11:03

Fred Foo