Linux系统环境下如何获得U盘拔插的信息
上一篇 /
下一篇 2008-05-07 16:47:54
/ 个人分类:技术文章
获得U盘的插入或者拔取得信息的传统方法是在内核级运行hotplug程序,相关参数
通过环境变量传递过来,再由hotplug通知其他关注hotplug的应用程序。这样的做法效率有些低,现在通过一种特殊类型的socket
netlink实现获取U盘拔插的信息。netlink专门用于内核空间和用户空间的异步通信。下面的例子可以监听内核的hotplug事件,源代码如下:
#include #include #include #include #include #include #include #include #include #include
#define UEVENT_BUFFER_SIZE 2048
static int init_hotplug_sock(void);
int main(int argc, char* argv[]) { int hotplug_sock = init_hotplug_sock(); while(1){ char buf[UEVENT_BUFFER_SIZE*2] = {0}; recv(hotplug_sock, &buf, sizeof(buf), 0); printf("%s\n", buf);
} return 0; }
static int init_hotplug_sock(void) { struct sockaddr_nl snl; const int buffersize = 16 * 1024 * 1024; int retval;
memset(&snl, 0x00, sizeof(struct sockaddr_nl)); snl.nl_family = AF_NETLINK; snl.nl_pid = getpid(); snl.nl_groups = 1; int hotplug_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
if (hotplug_sock == -1) { printf("error getting socket: %s", strerror(errno)); return -1; }
/* set receive buffersize */ setsockopt(hotplug_sock, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize)); retval = bind(hotplug_sock, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl));
if (retval < 0) { printf("bind failed: %s", strerror(errno)); close(hotplug_sock); hotplug_sock = -1; return -1; }
return hotplug_sock; } |
【51CTO编者注:其实如果是在Linux的字符环境下插上USB有时会有没有反应的情况,我们这时如何才能知道USB的实时状况呢?很简单一条命令就可以轻松搞定:
#Fdisk -l
下面是命令执行后的返回结果:
[root@new-host ~]# fdisk -l Disk /dev/sda: 80.0 GB, 80026361856 bytes 255 heads, 63 sectors/track, 9729 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Disk identifier: 0xcc4acc4a Device Boot Start End Blocks Id System /dev/sda1 * 1 1275 10241406 7 HPFS/NTFS /dev/sda2 1276 8418 57376147+ f W95 Ext'd (LBA) /dev/sda3 8419 9729 10530607+ 83 Linux /dev/sda5 1276 3825 20482843+ b W95 FAT32 /dev/sda6 8288 8418 1052226 82 Linux swap / Solaris /dev/sda7 3826 6120 18434556 83 Linux Partition table entries are not in disk order Disk /dev/sdb: 1010 MB, 1010826752 bytes 32 heads, 63 sectors/track, 979 cylinders Units = cylinders of 2016 * 512 = 1032192 bytes Disk identifier: 0x91f72d24 Device Boot Start End Blocks Id System /dev/sdb1 1 980 987808+ b W95 FAT32 |
其中最下面部分的的“Disk /dev/sdb: 1010 MB, 1010826752
bytes”显示了U盘的容量大约为1Gb,下面是相对应的设备号“/dev/sdb1 ”。这时再结合mount命令就可以知道次设备是否已经自动加载
到文件系统下,如果没有就可以使用
mount命令手动加载设备而就可以正常使用了。
导入论坛
引用链接
收藏
分享给好友
推荐到圈子
管理
举报
TAG: