检查 Bash 中是否存在 PID
我想停止 BASH 脚本的执行,直到进程关闭(我将 PID 存储在变量中)。我在想
while [PID IS RUNNING]; do
sleep 500
done
我见过的大多数例子都使用 /dev/null ,这似乎需要 root 权限。有没有办法不需要 root 就能做到这一点?
预先非常感谢您!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果
$pid
正在运行,kill -s 0 $pid
将返回成功,否则返回失败,而不实际向进程发送信号,因此您可以在中使用它>if
直接声明。wait $pid
将等待该进程,替换整个循环。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 yourif
statement directly.wait $pid
will wait on that process, replacing your whole loop.看起来你想要
当
$pid
完成时返回。否则,您可以使用它
来检查进程是否仍然存在(这比
kill -0 $pid
更有效,因为即使您不拥有 pid,它也能工作)。It seems like you want
which will return when
$pid
finishes.Otherwise you can use
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).您可能会查找
/proc/YOUR_PID
目录是否存在。You might look for the presence of
/proc/YOUR_PID
directory.ps --pid $pid >/dev/null
如果存在则返回 0,否则返回 1
ps --pid $pid &>/dev/null
returns 0 if it exists, 1 otherwise
我总是使用以下
tail -f /dev/null --pid $PID
。它不需要显式循环,并且不仅限于 shell 的子 pid。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.