TA的每日心情 | 开心 2017-12-22 08:59 |
---|
签到天数: 9 天 连续签到: 1 天 [LV.3]偶尔看看II
|
]Linux提供了hotplup(热插拔),udev和inotify机制帮助我们可以看到底层硬件设备发生了什么,从而能够更好地管理设备,给用户提供更好地服务。
Inotify通过如下三个系统调用和返回的文件描述符上的文件IO操作来使用。
Inotify的使用有如下几个步骤:
1、 创建‘inotify实例(inotify_init())
2、 添加一个watch(inotify_add_watch(fd,path,mask))
删除一个watch(inotify_rm_watch(fd,wd))
3、 文件事件用一个inotify_event结构表示- struct inotify_event {
- __s32 wd; /* watch descriptor */
- __u32 mask; /* watch mask */
- __u32 cookie; /* cookie to synchronize two event*/
- __u32 len; /* length (including nulls) of name */
- char name[0]; /* stub for possible name */
- };
复制代码- #include
- #include
- #include
- _syscall0(int, inotify_init)
- _syscall3(int, inotify_add_watch, int, fd, const char *, path, __u32, mask)
- _syscall2(int, inotify_rm_watch, int, fd, __u32, mask)
- char * monitored_files[] = {
- "./tmp_file",
- "./tmp_dir",
- "/mnt/sda3/windows_file"
- };
- struct wd_name {
- int wd;
- char * name;
- };
- #define WD_NUM 3
- struct wd_name wd_array[WD_NUM];
- char * event_array[] = {
- "File was accessed",
- "File was modified",
- "File attributes were changed",
- "writtable file closed",
- "Unwrittable file closed",
- "File was opened",
- "File was moved from X",
- "File was moved to Y",
- "Subfile was created",
- "Subfile was deleted",
- "Self was deleted",
- "Self was moved",
- "",
- "Backing fs was unmounted",
- "Event queued overflowed",
- "File was ignored"
- };
- #define EVENT_NUM 16
- #define MAX_BUF_SIZE 1024
-
- int main(void)
- {
- int fd;
- int wd;
- char buffer[1024];
- char * offset = NULL;
- struct inotify_event * event;
- int len, tmp_len;
- char strbuf[16];
- int i = 0;
-
- fd = inotify_init();
- if (fd < 0) {
- printf("Fail to initialize inotify.\n");
- exit(-1);
- }
- for (i=0; i<WD_NUM; wd="inotify_add_watch(fd," add (event- if { len) < buffer) - *)event (((char while *)buffer; inotify_event event len); len='%d.\n",' happens, printf(?Some offset="buffer;" MAX_BUF_SIZE)) buffer, while(len="read(fd," } wd_array[i].wd="wd;" exit(-1); wd_array[i].name); %s.\n?, for watch printf(?Can?t 0) (wd IN_ALL_EVENTS); wd_array[i].name, wd_array[i].name="monitored_files[i];" i++)>mask & IN_ISDIR) {
- memcpy(strbuf, "Direcotory", 11);
- }
- else {
- memcpy(strbuf, "File", 5);
- }
- printf("Object type: %s\n", strbuf);
- for (i=0; iwd != wd_array[i].wd) continue;
- printf("Object name: %s\n", wd_array[i].name);
- break;
- }
- printf("Event mask: %08X\n", event->mask);
- for (i=0; imask & (1<len;
- event = (struct inotify_event *)(offset + tmp_len);
- offset += tmp_len;
- }
- }
- }
复制代码 更多好内容可关注:华清远见 微信公众号,关注即送价值 399 的嵌入式相关电子书! |
|