#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define UEVENT_BUFFER_SIZE 2048
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)
{
return -1;
}
setsockopt(hotplug_sock, SOL_SOCKET, SO_RCVBUFFORCE,
&buffersize, sizeof(buffersize));
retval = bind(hotplug_sock, (struct sockaddr *) &snl,
sizeof(struct sockaddr_nl));
if (retval < 0)
{
close(hotplug_sock);
hotplug_sock = -1;
return -1;
}
return hotplug_sock;
}
int get_action(char *ptr)
{
if(strncmp(ptr, "add@", 4) == 0) {
return 0;
} else if(strncmp(ptr, "remove@", 7) == 0)
{
return 1;
} else if(strncmp(ptr, "change@", 7) == 0)
{
return 2;
} else {
return -1;
}
}
int is_usb_block(char *ptr)
{
char *usbp, *blkp;
usbp = strstr(ptr, "usb");
blkp = strstr(ptr, "block");
if(usbp && blkp)
{
return 1;
}
else
{
return 0;
}
}
char* get_partition(char *ptr)
{
FILE *fp;
char part_buff[128];
char *pos, *p;
static char part_nu[16][32];
int sum, i;
sum = i = 0;
fp = fopen("/proc/partitions", "r");
if(fp == NULL)
{
fclose(fp);
exit(1);
}
while(fgets(part_buff, sizeof(part_buff), fp))
{
pos = strstr(part_buff, ptr);
if(pos)
{
strcpy(part_nu[i], pos);
p = part_nu[i];
while(*p)
{
if(*p == '\n')
*p = '\0';
p++;
}
sum++;
i++;
}
}
fclose(fp);
sleep(1);
if(sum == 1)
{
printf("node is %s\n",part_nu[0]);
return part_nu[0];
}
else
{
for (i = 1; i < sum; i++)
{
printf("node is %s\n",part_nu[i]);
return part_nu[i];
}
}
return NULL;
}
void get_usb_node(char *ptr, char *node)
{
char *p;
printf("%s\n",ptr);
p = strrchr(ptr, '/');
p++;
strcpy(node, p);
p = node;
while(*p)
{
if(*p == '\n')
*p = '\0';
p++;
}
}
int main(int argc, char *argv[])
{
char buf[UEVENT_BUFFER_SIZE*2] = {0};
char dev_node[8] = {0};
int sock_fd, act, i;
pid_t pid;
sock_fd = init_hotplug_sock();
if (sock_fd < 0) {
return 1;
}
while(1) {
recv(sock_fd, &buf, sizeof(buf), 0);
act = get_action(buf);
if(act == 0) {
if(is_usb_block(buf)) {
get_usb_node(buf, dev_node);
if(dev_node[3] == '\0') {
get_partition(dev_node);//返回节点
}
}
}
}
return 0;
}
阅读(1469) | 评论(0) | 转发(0) |