/proc/scsi/下的文件夹usb-storage 在没有插入 U盘的时候,它是不存在的,故我们判断U盘的插入还是移出 就是通过判断opendir这个目录成功还是失败来判断。
1 #include<stdio.h>
2 #include<sys/types.h>
3 #include<dirent.h>
4 #include<stdlib.h>
5
6 int main(int argc , char* argv[])
7 {
8 DIR *dir;
9 int usb_bool = 0;
10
11 while(1)
12 {
13 /*这个循环体里是守护进程要做的工作*/
14
15 if((dir = opendir("/proc/scsi/usb-storage" )) != NULL) //存储设备是插上了
16 {
17 usb_bool = 1;
18 printf("up %p /n" ,dir);
19 closedir(dir);
20 }
21 else
22 {
23 printf("down %p/n" ,dir);
24 usb_bool = 0; //拔下来的时候一定要清0
25 }
26 sleep(3);
27 }
28
29 }
输出结果:
magic@ubuntu:~/work/Linux_System_Program/digital--005$ ./test_usb
up 0x8ecd008
up 0x8ecd008
down (nil)
down (nil)
down (nil)
down (nil)
down (nil)
down (nil)
down (nil)
up 0x8ecd008
up 0x8ecd008
up 0x8ecd008
up 0x8ecd008
up 0x8ecd008
down (nil)
down (nil)
down (nil)
down (nil)
down (nil)
up 0x8ecd008
up 0x8ecd008
up 0x8ecd008
有的时候,如果由于你opendir后都忘记了closedir,则有时候会造成 你把U盘移出了,仍然可以读取成功,可以尝试重启计算机。。。
本文介绍了一种通过检查/proc/scsi/usb-storage目录是否存在来判断U盘是否已连接的方法,并提供了一个简单的C语言程序示例。
3898





