Saturday, September 5, 2009

Shell Script for USB Device Insertion/Removal Detection : Embedded Linux and Desktop Linux

Recently i have succeeded to write a shell script to detect the USB device insertion as well as removal in Desktop Linux and as well as fressscale's Embedded Linux.

First i have done for Embedded Linux in very simple way. But i was not sure about its working on all Linux distributions. Bcoz in some Linux, there could be HDD devices as /dev/sda1, /dev/sda2 and so on. Hence i have decided to make it work in Desktop linux and after, definitely that will work on all embedded linux also.

But my expectation was wrong. What i have executed on desktop Linux which didnt work on Embedded Linux on target. I didnt think about that's reason. Anyway after i have modified the same script to make work on Embedded linux.

Lets share tha same.

Script for Desktop Linux:

while [ 1 ]
do
set /dev/sd[a-z][1-9]
d=$#
while [ 1 ]
do
set /dev/sd[a-z][1-9]
if [ $# -gt "$d" ]
then
break
fi
echo not yet "$d"
sleep 1
done
echo "It has come $#"
j=0
for p in "$@"
do
arr[$j]=$p
j=`expr $j+1`
done
echo This is the node "${arr[$#-1]}"
mount -t vfat ${arr[$#-1]} /mnt/DEVICE
ls /mnt/DEVICE
#------------------------------------------#
d1=$#
while [ 1 ]
do
set /dev/sd[a-z][1-9]
if [ $# -lt "$d1" ]
then
break
fi
echo "Still connected"
sleep 1
done
echo "Disconnected now"
umount /mnt/DEVICE
done
done

But. this script should be running in background. Will generate the signal when device is detected or new node has come under /dev/ directory.

For which process signal has to be sent, that's PID is the input for 'kill' command. Process's PID i am getting here using 'grep'. Process name is the input for grep and 'ps' has to executed before 'grep' to get PID of the process.

When device is detected, i am mounting the same to a specific path, here is /mnt/DEVICE. In my proogram, i will read the contents of the device from the same path.

Actually, we were using thread (pthread_create) and 'mount' system call to detect the device insertion/removal. That program also i will give in y next post which could help or could give more idea to others.

No comments:

Post a Comment