BASH - Check if PID Exists

2019-03-10 23:54发布

I want to stall the execution of my BASH script until a process is closed (I have the PID stored in a variable). I'm thinking

while [PID IS RUNNING]; do
sleep 500
done

Most of the examples I have seen use /dev/null which seems to require root. Is there a way to do this without requiring root?

Thank you very much in advance!

标签: bash shell pid
5条回答
孤傲高冷的网名
2楼-- · 2019-03-11 00:16

I always use the following tail -f /dev/null --pid $PID. It doesn't require explicit loop and isn't limited to your shell's children pids only.

查看更多
Bombasti
3楼-- · 2019-03-11 00:22

ps --pid $pid &>/dev/null

returns 0 if it exists, 1 otherwise

查看更多
The star\"
4楼-- · 2019-03-11 00:24

kill -s 0 $pid will return success if $pid is running, failure otherwise, without actually sending a signal to the process, so you can use that in your if statement directly.

wait $pid will wait on that process, replacing your whole loop.

查看更多
虎瘦雄心在
5楼-- · 2019-03-11 00:29

You might look for the presence of /proc/YOUR_PID directory.

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-03-11 00:31

It seems like you want

wait $pid

which will return when $pid finishes.

Otherwise you can use

ps -p $pid

to check if the process is still alive (this is more effective than kill -0 $pid because it will work even if you don't own the pid).

查看更多
登录 后发表回答