Udev 未在脚本内运行 xinput 命令

Udev 未在脚本内运行 xinput 命令

我试图做到这一点,以便当我连接外部鼠标时我可以自动重新映射按钮。我可以手动重新映射按钮xinput set-button-map $mouse_id $button_map

但是,我在自动执行此操作时遇到困难。我目前正在尝试让 udev 在设备连接时运行脚本。我有这个规则/etc/udev/rules.d/my_rule.rules

ATTRS{idVendor}=="dummy", ATTRS{idProduct}=="dummy", RUN+="/bin/bash /path/to/my_script.sh"

看起来my_script.sh像这样:

#!/bin/bash
out_file=/path/to/out.txt
mouse_id=dummy
button_map=dummy
# button map before
/usr/bin/xinput get-button-map $mouse_id >> $out_file
/usr/bin/xinput set-button-map $mouse_id $button_map
# button map after
/usr/bin/xinput get-button-map $mouse_id >> $out_file

如果我从终端调用该脚本,该脚本将完全按照预期运行,但问题是在 udev bash 环境中 xinput 根本不运行。对它的三个调用都没有执行任何操作。即使类似的事情也/usr/bin/xinput >> $out_file无济于事。但是,类似的操作echo foobar >> $out_file确实会将输出放入 out 文件中。

我一直在寻找类似这样的各种东西编写 udev 规则指南我已经按照其他一些帖子的建议更改了对绝对路径的所有各种调用,但我无法弄清楚。

答案1

我继续寻找并发现这个帖子在超级用户 stackexchange 上,它说 xinput 需要设置 DISPLAY 和 XAUTHORITY 环境变量,我能够修改我的脚本并且它起作用了!但是,我还必须添加睡眠并使其在后台运行。这是我的最终脚本:

my_rule.rules:

ATTRS{idVendor}=="dummy", ATTRS{idProduct}=="dummy", ACTION=="add", RUN+="/path/to/my_sript.sh"

my_script.sh:

#!/usr/bin/bash
out_file=/path/to/out.txt
# run normal if given argument, start new in background else
if [[ $1 ]]
then
    sleep 1
    mouse_id="my_mouse's_id"
    xenv="env DISPLAY=:0 XAUTHORITY=/home/my_name/.Xauthority"
    # button map before
    $xenv /usr/bin/xinput get-button-map "$mouse_id" >> $out_file
    $xenv /usr/bin/xinput set-button-map "$mouse_id" 2 3 2 4 5 6 7 1 9
    # button map after
    $xenv /usr/bin/xinput get-button-map "$mouse_id" >> $out_file
    echo finished >> $out_file
else
    echo running > $out_file
    # run it, but detached in the background
    /path/to/my_script.sh run_normal & 
fi

我还想向其他人指出,当我插入鼠标时,udev 会调用该脚本 18 次,但这似乎不是问题。

相关内容