我的目标是在USB闪存驱动器插入时运行Python脚本。我编写了一个udev规则和一个在该规则中调用的shell脚本。
udev规则:/etc/udev/rules.d/10-usb.rules
KERNEL=="sd*[!0-9]|sr*", ENV{ID_SERIAL}!="?*", SUBSYSTEMS=="usb", RUN+="/home/Hypotheron/Desktop/script.sh"
script.sh:
#!/bin/sh
echo 'Hello, world.' > /home/Hypotheron/Desktop/foo.txt
#/home/Hypotheron/Desktop/job.py & exit
我的Python文件的第一行是:
#!/usr/bin/python
我也做了以下命令:
chmod +x job.py
chmod +x script.sh
在script.sh中,当取消注释写入foo.txt的行时,每次闪存驱动器插入都会创建foo.txt文件。
当我评论该行并取消注释运行Python文件的行时,它不起作用。
通过终端运行script.sh在两种情况下均可正常工作,但在插入闪存驱动器时,只有foo.txt案例有效。
任何帮助都将不胜感激。
答案 0 :(得分:3)
RUN{type}
Add a program to the list of programs to be executed after
processing all the rules for a specific event, depending on "type":
"program"
Execute an external program specified as the assigned value. If
no absolute path is given, the program is expected to live in
/lib/udev; otherwise, the absolute path must be specified.
This is the default if no type is specified.
"builtin"
As program, but use one of the built-in programs rather than an
external one.
The program name and following arguments are separated by spaces.
Single quotes can be used to specify arguments with spaces.
This can only be used for very short-running foreground tasks.
Running an event process for a long period of time may block all
further events for this or a dependent device.
Starting daemons or other long-running processes is not appropriate
for udev; the forked processes, detached or not, will be
unconditionally killed after the event handling has finished.
从udev手册页,请特别注意最后两段 我的猜测是,你发现了无条件的杀戮部分
1年后编辑:
在有人投票之后我重新审视了这个问题,我已经解决了问题,即root
(正在运行此流程的人)没有对某些事情(例如notify-send
)或启动而言必不可少的X终端条目一个Gui程序,如前所述,事件发生后仍然存在杀戮过程
当插入USB设备时,以下内容向终端发送通知并启动wxPython Gui程序。
剧本:
#!/bin/sh
DISPLAY=:0
export DISPLAY
/usr/bin/notify-send "Usb Device detected" "Starting Reminder program" | at now
/usr/bin/python3 /home/rolf/reminders/reminders2.1.0/reminder.py | at now
通过定义DISPLAY,我们可以解决根本问题的无X条款
通过将我们希望运行的命令传递给at
程序以及现在运行它的指令,我们避免了udev杀死进程。
/lib/udev/rules.d/10-usbinsert.rules文件:
KERNEL=="sd*[!0-9]|sr*", ENV{ID_SERIAL}!="?*", SUBSYSTEMS=="usb", RUN+="/usr/bin/sudo -u rolf /home/rolf/script.sh &"
我希望这有助于或让你朝着正确的方向前进。