Search code examples
pythonbashraspberry-pi2usb-driveudev

Run script with udev after USB plugged in on a Raspberry Pi


I am trying to run a script from a udev rule after any USB drive has been plugged in.

When I run the script manually, after the USB is mounted normally, it will run fine. The script calls a Python program to run, and the Python program uses a file on the USB drive. There aren't any issues there.

If I make the script to simply log the date in a file, that works just fine. So I know my udev rule and my script work fine, each on their own.

The issue seems to come up when udev calls the script, and then the script calling the Python program and the Python program does not run right. I believe it to be that the USB drive has not finished mounting before the Python script runs. When watching top, my script begins to run, Python begins to run, they both end, and then I get the window popup of my accessing the files on my USB drive.

So I tried having script1.sh call script2.sh call python.py. I tried having script.sh call python1.py call python2.py. I tried adding a sleep function, both in the script.sh and python.py. I tried in the rule, RUN+="/home/pi/script.sh & exit". I tried exit in the files. I tried disown in the files.

What else can I try?


Solution

  • Well, you probably described you problem. The mount process is too slow. You can mount your USB device from your script.sh script.

    Also, you probably need to disable automatic USB device mount for your system or the specific device only.

    If you add a symbolic link to your udev rule, e.g. SYMLINK+="backup", then you can mount this device by:

    mkdir -p /path/to/foo mount -t ext4 /dev/backup /path/to/foo