BASH - Check if PID Exists

前端 未结 5 1553
情歌与酒
情歌与酒 2021-02-02 10:43

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 5         


        
相关标签:
5条回答
  • 2021-02-02 11:04

    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.

    0 讨论(0)
  • 2021-02-02 11:05

    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).

    0 讨论(0)
  • 2021-02-02 11:07

    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.

    0 讨论(0)
  • 2021-02-02 11:11

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

    returns 0 if it exists, 1 otherwise

    0 讨论(0)
  • 2021-02-02 11:20

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

    0 讨论(0)
提交回复
热议问题