如何在 shell 脚本中观察进程是否已死亡?
我正在运行一个 shell 测试程序,我可以查看进度条,但是当我运行它时,我不断收到一元错误。 Kill -0 是杀死 shell 中子进程的方法吗? 或者还有另一种方法来测试我的进程是否已经死亡? 这是我的代码,用于运行进度条直到我的命令结束:
#!/bin/sh
# test my progress bar
spin[0]="-"
spin[1]="\\"
spin[2]="|"
spin[3]="/"
sleep 10 2>/dev/null & # run as background process
pid=$! # grab process id
echo -n "[sleeping] ${spin[0]}"
while [ kill -0 $pid ] # wait for process to end
do
for i in "${spin[@]}"
do
echo -ne "\b$i"
sleep 0.1
done
done
enter code here
I'm running a shell test program that I can view a progress bar but when I run it I keep getting a unary error . Is kill -0 a way to kill a subprocess in shell ?
Or is there another method to test if my process has died?
heres my code to run a progress bar until my command ends:
#!/bin/sh
# test my progress bar
spin[0]="-"
spin[1]="\\"
spin[2]="|"
spin[3]="/"
sleep 10 2>/dev/null & # run as background process
pid=$! # grab process id
echo -n "[sleeping] ${spin[0]}"
while [ kill -0 $pid ] # wait for process to end
do
for i in "${spin[@]}"
do
echo -ne "\b$i"
sleep 0.1
done
done
enter code here
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
1. Kill -0 是在 shell 中终止子进程的方法吗?
在 Linux 操作系统上,
kill -0
只是尝试终止进程并查看会发生什么的一种方法,“0”是不是 POSIX 信号,它什么也不做。如果进程正在运行,
kill
将返回0
,如果没有,则返回1
。ps $pid >/dev/null 2>&1
可以完成相同的工作。要终止进程,通常使用
SIGQUIT/3
(退出程序)或SIGKILL/9
(终止程序);该进程可以捕获该信号并干净退出,也可以忽略该信号,因此操作系统必须“快速而肮脏”地终止它。2. test 和 '['
/bin/[
),并期待您未正确提供的内容。while
的语法为while list;做清单; done
其中list
将返回退出代码,因此您不必使用其他内容。3.我如何在 shell 脚本中观察进程是否已终止?
就像您所做的那样,下面的代码将完成这项工作:
CAVEATS
我使用
/bin/bash
作为解释器,因为某些 Bourne Shell (sh
) 无法支持使用数组(即spin[n]< /代码>)。
1. Is kill -0 a way to kill a subprocess in shell ?
On Linux OS,
kill -0
is just a way to try to kill a process and see what happens, '0' is not a POSIX signal, it does nothing at all.If the process is running,
kill
will return0
, if not, it will return1
.ps $pid >/dev/null 2>&1
could do the same job.To kill a process, one generally use the
SIGQUIT/3
(quit program) orSIGKILL/9
(terminate program) ; the process could trap the signal and make a clean exit, or it could ignore the signal so the OS has to terminate it 'quick and dirty'.2. test and '['
/bin/[
), and expect something you didn't provide correctly.while
iswhile list; do list; done
wherelist
will return an exit code, so you don't have to use something else.3. how do I watch for a process to have died in shell script?
Like you did, the code below will do the job:
CAVEATS
I use
/bin/bash
as interpreter, as some of the Bourne Shell (sh
) could not support the use of an array (iespin[n]
).在后台运行微调器并在进程(在前台运行)终止时终止它可能会更干净。或者,您可以打开另一个文件描述符并在后台进程终止后向其中写入一些内容,然后让主进程块进行读取。例如:
It's probably cleaner to run the spinner in the background and kill it when the process (running in the foreground) terminates. Or, you could open another file descriptor and write something into it after the background process terminates, and have the main process block on a read. eg: