一个c4droid小demo
c4droid吧
全部回复
仅看楼主
level 1
qwqq525 楼主
demo功能:检测otg插入
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#define UEVENT_BUFFER_SIZE 2048
int main(void)
{
struct sockaddr_nl client;
struct timeval tv;
int CppLive, rcvlen, ret;
fd_set fds;
int buffersize = 1024;
CppLive = socket(AF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT);
memset(&client, 0, sizeof(client));
client.nl_family = AF_NETLINK;
client.nl_pid = getpid();
client.nl_groups = 1; /* receive broadcast message*/
setsockopt(CppLive, SOL_SOCKET, SO_RCVBUF, &buffersize, sizeof(buffersize));
bind(CppLive, (struct sockaddr*)&client, sizeof(client));
while (1) {
char buf[UEVENT_BUFFER_SIZE] = { 0 };
FD_ZERO(&fds);
FD_SET(CppLive, &fds);
tv.tv_sec = 0;
tv.tv_usec = 100 * 1000;
ret = select(CppLive + 1, &fds, NULL, NULL, &tv);
if(ret < 0)
continue;
if(!(ret > 0 && FD_ISSET(CppLive, &fds)))
continue;
/* receive data */
rcvlen = recv(CppLive, &buf, sizeof(buf), 0);
if (rcvlen > 0) {
printf("%s\n", buf);
/*You can do something here to make the program more perfect!!!*/
}
}
close(CppLive);
return 0;
}
欢迎大家试试
截图2楼
2017年03月12日 07点03分 1
level 1
qwqq525 楼主
2楼上图:
本人博客:http://www.bluexiang.com
2017年03月12日 08点03分 2
你也玩emlog啊,
2017年03月13日 01点03分
level 13
select(....,&tv);把tv传入Null不更好一点?
2017年03月12日 09点03分 4
level 13
而且你这个不是专门检测otg插入吧?你所有文件变化都输出了!
2017年03月12日 10点03分 5
level 13
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<asm/types.h>
//该头文件需要放在netlink.h前面防止编译出现__kernel_sa_family未定义#include<sys/socket.h>
#include<linux/netlink.h>
void MonitorNetlinkUevent()
{
intsockfd;
struct sockaddr_nl sa;
intlen;
char buf[4096];
struct iovec iov;
struct msghdr msg;
inti;
memset(&sa,0,sizeof(sa));
sa.nl_family=AF_NETLINK;
sa.nl_groups=NETLINK_KOBJECT_UEVENT;
sa.nl_pid=0;//getpid();bothisok
memset(&msg,0,sizeof(msg));
iov.iov_base=(void*)buf;
iov.iov_len=sizeof(buf);msg.msg_name=(void*)&sa;
msg.msg_namelen=sizeof(sa);
msg.msg_iov=&iov;
msg.msg_iovlen=1;
sockfd=socket(AF_NETLINK,SOCK_RAW,NETLINK_KOBJECT_UEVENT);
if(sockfd==-1) printf("socket creating failed:%s\n",strerror(errno));if(bind(sockfd,(struct sockaddr*)&sa,sizeof(sa))==-1)
printf("bind error:%s\n",strerror(errno));
len=recvmsg(sockfd,&msg,0);
if(len<0)
printf("receive error\n");
elseif(len<32||len>sizeof(buf))
printf("invalid message");
for(i=0;i<len;i++)
if(*(buf+i)=='\0')
buf[i]='\n';
printf("received %d bytes\n%s\n",len,buf);
}
intmain(intargc,char**argv)
{
MonitorNetlinkUevent();
return 0;
}
2017年03月12日 10点03分 6
大佬,[吐舌]看起来像是接受Intent广播的样子。
2017年03月13日 01点03分
@DXKite netlink异步通信
2017年03月15日 00点03分
level 13
好帖收藏了
2017年03月12日 11点03分 7
level 7
[滑稽]
2017年03月13日 03点03分 8
level 11
Mark,膜拜大神 [滑稽]
2017年03月13日 09点03分 9
level 1
这是什么意思,请大神讲解一下,新人不懂[吐舌][吐舌]
2017年03月13日 13点03分 10
netlink异步通讯
2017年03月15日 00点03分
1