// 这篇文章对 IN_DELETE_SELF的理解出错.
前段时间写 inotify 相关的程序, 发现当时间为 IN_DELETE_SELF或 IN_MOVE_SELF 时 event 结构中 name 属性不能 printf.
我觉得不应该, 今天特意写代码测试下.
#include <stdio.h> #include <sys/inotify.h> #include <unistd.h> #include <stdlib.h> #define BUF_LEN 1024 #define EVENT_NUM 12 static char *event_str[EVENT_NUM] = { "IN_ACCESS", "IN_MODIFY", "IN_ATTRIB", "IN_CLOSE_WRITE", "IN_CLOSE_NOWRITE", "IN_OPEN", "IN_MOVED_FROM", "IN_MOVED_TO", "IN_CREATE", "IN_DELETE", "IN_DELETE_SELF", "IN_MOVE_SELF" }; int main(int argc, char *argv[]) { pid_t pid; if(argc < 2) { printf("%s dir\n", argv[0]); return -1; } pid = fork(); if(pid == 0) { sleep(20); remove(argv[0]); exit(-1); } else if(pid < 0) { printf("fork failed\n"); return -1; } set_watch(argv[1]); return 0; } int set_watch(char *dir) { int fd, wd; int i; char buf[BUF_LEN]; int len, nread; struct inotify_event *event; if((fd = inotify_init()) == -1) { printf("inotify_init failed\n"); return -1; } wd = inotify_add_watch(fd, dir, IN_ALL_EVENTS); if(wd == -1) { printf("inotify_add_watch %s failed\n", dir); return -1; } while((len = read(fd, buf, BUF_LEN)) > 0) { buf[BUF_LEN-1] = '\0'; nread = 0; while(len) { event = (struct inotify_event *)&buf[nread]; for(i=0; i<EVENT_NUM; i++) { if((event->mask >> i) & 1) { printf("%s --- %s\n", event->name, event_str[i]); break; } } nread = nread + sizeof(struct inotify_event) + event->len; len = len - (sizeof(struct inotify_event) + event->len); } } inotify_rm_watch(fd, wd); close(fd); return 0; }
运行程序显示:
ts_mv_del_self --- IN_DELETE
正常. 看来我以前的代码有问题了.