does the pid of background process show in /proc?

Hi all,
I'm reading <advanced bash scripting> and there is a example to kill a background process in a limited time,as shown below:

#! /bin/bash

#set -n

TIMEOUT=$1
count=0

hanging_jobs & {
	while ((count < TIMEOUT));do
	   eval '[ ! -d "/proc/$!" ] && ((count = TIMEOUT))'
		((count++))
		sleep 1
		echo $!
	done

	eval '[ -d "/proc/$!" ] && kill -15 $! '
}

I don't know why it use eval (is it necessary?)and i can't understand the meaning of

[ ! -d "/proc/$!" ] && ((count = TIMEOUT))

besides,the book says that /proc is where information about running process is found,but i can't find the relative directory of my background process.why?

I tried that code. I set TIMEOUT to 7 and I replaced hanging_jobs with "sleep 3" and "sleep 100". The code works fine. I removed the evals and tried it again. Still works fine. While those eval's are harmless, I cannot see any reason to use them. The code

[ ! -d "/proc/$!" ] && ((count = TIMEOUT))

tests to see the the directory is missing. If so it sets count to TIMEOUT. This makes the loop stop.

Not all systems have a /proc filesystem. Maybe yours does not. This undermines to portability of that code. A more portable way to test if a process exists is to use "kill -0 $pid". This won't kill the process but it will fail the process is not there.

If anyone has any thoughts on why those eval's are useful I hope they post. They have me beat. :confused:

1 Like

thanks so much.i thought the "=" to be a equal rather than a assign operator:wall:

my operating system is Linux2.6.35,it has the /proc,but the relative file(directory) of running background process can't be found in it in this example.

What did you replace hanging_jobs with? The directory won't exist if the job finishes before you check.

yeah,i use the "sleep 10" and i printed the $_ every second and during that period,i checked the /proc and didn't find it. So,in your linux,it works fine?

What's this $_? The PID is $!

The evals do nothing, yes.

Could you copy-paste your script exactly as you have it? I think there must be some slight error somewhere that's throwing it off.

background processes are no more special than any other process as far as the kernel's concerned and definitely do appear in /proc/ in any linux I can think of.

1 Like

thanks for your reply,i'm sorry i made a careless mistake here,in my script i used $!:),here is my code:

  1 #! /bin/bash
  2 
  3 #set -n
  4 
  5 TIMEOUT=$1
  6 count=0
  7 
  8 sleep $TIMEOUT & {
  9    while ((count < TIMEOUT));do
 10       eval '[ ! -d "/proc/$!" ] && ((count = TIMEOUT))'
 11       ((count++))
 12       sleep 1
 13       echo $!
 14    done
 15 
 16    eval '[ -d "/proc/$!" ] && kill -15 $! '
 17 }
~    

---------- Post updated at 10:05 PM ---------- Previous update was at 10:02 PM ----------

Thanks to all above,it shows up in /proc,maybe i'm too careless to find it.....