我正在制作一个bash脚本,需要注意手动关闭的CD抽屉。驱动器很细,因此没有开/关电机。我需要监控什么才能显示抽屉的状态或其关闭事件?
我正在运行Ubuntu 12.04服务器。
答案 0 :(得分:4)
您可以使用Perl,Python或Ruby等解释语言调用ioctl
内核来查询驱动器状态。
function check_disk_tray_perl {
perl -e 'use POSIX; sysopen(FD, $ARGV[0], O_RDONLY|O_NONBLOCK) || die "Failed to open device ${ARGV[0]}\n"; my $r = ioctl(FD, 0x5326, 0); exit ($r > 0 ? $r & 0x01 ? 0 : 1 : 2);' "$1"
}
function check_disk_tray_ruby {
ruby -e 'require "fcntl"; dev = ARGV[0]; begin fd = IO::sysopen(dev, Fcntl::O_RDONLY|Fcntl::O_NONBLOCK); io = IO.new(fd); rescue; $stderr.puts "Failed to open device #{dev}."; exit 2; end; r = io.ioctl(0x5326, 0); exit (r > 0 ? (r & 0x01) == 1 ? 0 : 1 : 2);' "$1"
}
function check_disk_tray_python {
python -c 'import os, sys, fcntl
dev = str(sys.argv[1])
try:
fd = os.open(dev, os.O_RDONLY|os.O_NONBLOCK)
except:
sys.stderr.write("Failed to open device " + dev + ".\n")
exit(2)
r = fcntl.ioctl(fd, 0x5326, 0)
os.close(fd)
exit(2 if (r <= 0) else 0 if (r & 1) else 1)
' "$1"
}
您还可以在运行时使用gcc编译代码:
function check_disk_tray_gcc {
local OUTPUT_BINARY="/tmp/check_disk_tray_gcc_$((RANDOM))"
local FLAGS=(-O2 -pipe -fomit-frame-pointer)
local R
gcc "${FLAGS[@]}" -o "$OUTPUT_BINARY" -xc - <<EOF
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/cdrom.h>
int main(int argc, char** argv)
{
if (argc != 2) {
fprintf(stderr, "Invalid number of arguments.\n");
return 2;
}
char* file = argv[1];
int fd = open(file, O_RDONLY|O_NONBLOCK);
if (fd < 0) {
fprintf(stderr, "Failed to open file %s.\n", file);
return 2;
}
int r = ioctl(fd, CDROM_DRIVE_STATUS, 0);
return (r > 0 ? r & 1 ? 0 : 1 : 2);
}
EOF
if [[ $? -ne 0 || ! -f "$OUTPUT_BINARY" ]]; then
R=2
else
"$OUTPUT_BINARY" "$1"
R=$?
fi
rm -f "$OUTPUT_BINARY"
return "$R"
}
包装功能:
function check_disk_tray {
if type -P perl >/dev/null; then
check_disk_tray_perl "$1"
elif type -P ruby >/dev/null; then
check_disk_tray_ruby "$1"
elif type -P python >/dev/null; then
check_disk_tray_python "$1"
elif type -P gcc >/dev/null; then
check_disk_tray_gcc "$1"
else
echo "No tool usable for checking disk tray." >&2
return 2
fi
}
使用示例:
#!/bin/bash
# ---- Place the above codes here. ----
check_disk_tray "$(readlink -f /dev/cdrom)"
case "$?" in
0)
echo "Tray is closed."
;;
1)
echo "Tray is open."
;;
2|*)
echo "General failure."
;;
esac
答案 1 :(得分:0)
您可以为ascpi事件解析/var/log/messages
。
另请查看适用于UBUNTU的dbus-monitor