![如果程序已在运行并已打开特定文件,则阻止启动该程序](https://linux22.com/image/210964/%E5%A6%82%E6%9E%9C%E7%A8%8B%E5%BA%8F%E5%B7%B2%E5%9C%A8%E8%BF%90%E8%A1%8C%E5%B9%B6%E5%B7%B2%E6%89%93%E5%BC%80%E7%89%B9%E5%AE%9A%E6%96%87%E4%BB%B6%EF%BC%8C%E5%88%99%E9%98%BB%E6%AD%A2%E5%90%AF%E5%8A%A8%E8%AF%A5%E7%A8%8B%E5%BA%8F.png)
我需要将一a_command myfile
对限制为只有一个实例。
- 在我的具体情况下,我跑
qemu-system-x86_64 [options] -drive file=myfile.img,format=raw
- 该脚本应检查两者是否
qemu-system-x86_64
正在运行和文件myfile.img
已打开。我认为如果myfile.img
任何程序是 rw-open 的话,阻止运行会更安全。
我怎样才能做到这一点?
答案1
虽然 Stephen Kitt 在评论中指出,这可能首先是不必要的,但您仍然可以通过组合pidof
和 来检查特定二进制文件是否正在运行以及特定文件是否已打开lsof
。
pidof
将找到运行作为参数给出的程序的进程的 PID。如果至少找到一个实例,它将返回“true”,否则返回“false”。输出与此处无关,并通过重定向来抑制/dev/null
lsof
将列出打开特定文件的所有程序。如果至少一个程序具有打开的文件描述符,则返回“true”,否则返回“false”。
一个简单的检查如下所示:
#!/bin/bash
# Check if program is running and image file open. If yes, then exit right away.
if pidof qemu-system-x86_64 >/dev/null && lsof myfile.img >/dev/null
then
printf -- "An instance of qemu is running and file 'myfile.img' is open. Exiting!\n"
exit 1
fi
# If at least one is not the case, execute your code here
在更复杂的设置中,您可以检查它是否确实qemu-system-x86_64
打开了您的myfile.img
:
if lsof myfile.img | grep -q '^qemu-system-x86_64'
then
printf -- "File 'myfile.img' is opened by program 'qemu-system-x86_64'. Exiting!"
exit 1
fi
请注意,用于grep
检查程序名称是否是输出行上的第一项要求您的程序名称不包含 RegEx 特有的字符。