5

我正在编写一个 bash 脚本,该脚本需要监视 CD 抽屉是否被手动关闭。该驱动器是纤细的,因此它没有打开/关闭电机。我需要监控什么来显示抽屉的状态或关闭的事件?

我正在运行 Ubuntu 12.04 服务器。

4

2 回答 2

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
于 2013-09-03T11:12:04.033 回答
0

您可以解析/var/log/messagesascpi 事件。

还可以查看在 UBUNTU 中工作的dbus-monitor

于 2013-09-02T20:40:54.517 回答