Ale*_*lls 19 bash process shell-script proc
假设我手头有一个pid, mypid=$$
是否有一些 bash/system 命令我可以用给定的 pid 来监听该进程的退出?
如果不存在带有 mypid 的进程,我想该命令应该只是失败。
Ale*_*lls 34
我从这个答案中得到了我需要的东西:https : //stackoverflow.com/a/41613532/1223975
..结果 usingwait <pid> 仅当该 pid 是当前进程的子进程时才有效。
但是,以下内容适用于任何过程:
Linux:
tail --pid=$pid -f /dev/null
Run Code Online (Sandbox Code Playgroud)
达尔文(要求$pid有打开的文件):
lsof -p $pid +r 1 &>/dev/null
Run Code Online (Sandbox Code Playgroud)
Linux:
timeout $timeout tail --pid=$pid -f /dev/null
Run Code Online (Sandbox Code Playgroud)
达尔文(要求$pid有打开的文件):
lsof -p $pid +r 1m%s -t | grep -qm1 $(date -v+${timeout}S +%s 2>/dev/null || echo INF)
Run Code Online (Sandbox Code Playgroud)
可移植的方法是使用kill进行轮询,即类似:
until kill -s 0 "$pid" 2>/dev/null; do sleep 1; done
Run Code Online (Sandbox Code Playgroud)
这不需要诸如 GNU tail 或 lsof 之类的不可移植命令,并且在 bash 中,仅调用一个外部命令,即 sleep。GNU tail 可能更高效一些,因为它是用 C 编写的(理论上可以利用高级函数,例如pidfd_open),并且 lsof 可能会产生大量开销。
粗略的超时可以通过计算循环迭代的次数来实现。
一种仅适用于一个服务员的可移植性稍差的解决方案是使用 ptrace(2),它没有可移植的 shell 接口,但可以在某些系统上使用 strace 命令进行访问:
strace -e exit -e signal=none -p "$pid"
Run Code Online (Sandbox Code Playgroud)
小智 2
您可以使用 bash 内置命令wait:
$ sleep 10 &
[2] 28751
$ wait 28751
[2]- Done sleep 10
$ help wait
wait: wait [-n] [id ...]
Wait for job completion and return exit status.
Waits for each process identified by an ID, which may be a process ID or a
job specification, and reports its termination status. If ID is not
given, waits for all currently active child processes, and the return
status is zero. If ID is a a job specification, waits for all processes
in that job's pipeline.
If the -n option is supplied, waits for the next job to terminate and
returns its exit status.
Exit Status:
Returns the status of the last ID; fails if ID is invalid or an invalid
option is given.
Run Code Online (Sandbox Code Playgroud)
它使用系统调用waitpid()..
$ whatis waitpid
waitpid (2) - wait for process to change state
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15555 次 |
| 最近记录: |