2

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?

  • ps. Use ps to find out what process is the child of $!. – AlexP Jun 3 '18 at 11:09
2

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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.