5

I'm using the timeout utility inside a bash script to run a command for a given time (e.g., timeout -s SIGINT 500s ./my_script). I want to monitor the process myscript to see how much CPU/memory it uses (e.g. with the htop -p <pid> command).

I know that when a process is started in background (with &) I can get its pid programmatically by retrieving the $! variable. The problem is that timeout spawns a new subprocess and with the $! variable I get the "pid of timeout" and not the pid of myscript.

How can you retrive the pid of the subprocess spawned by timeout?

0

1 Answer 1

3

Give timeout a chance to start the script, then ask ps for the process whose parent is timeout:

timeout -s SIGINT 500s ./my_script &
bgpid=$!
sleep 1
p=$(ps -o pid= --ppid "$bgpid")
echo The pid you want is: "$p"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .