|
发表于 2003-9-18 19:00:15
|
显示全部楼层
这个可以实现文件监视,我大概写了一段代码,主要部分和上面的文章一样:
- #define _GNU_SOURCE
- #include <fcntl.h>
- #include <signal.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- static volatile int event_fd;
- static void handler(int sig, siginfo_t *si, void *data)
- {
- event_fd = si->si_fd;
- }
- int
- main(void)
- {
- int fdd, fd;
- struct sigaction act;
- char buf[100];
- int n;
-
- act.sa_sigaction = handler;
- sigemptyset(&act.sa_mask);
- act.sa_flags = SA_SIGINFO;
- sigaction(SIGRTMIN, &act, NULL);
-
- fd = open("ttxx", O_RDONLY); /* 打开需要监视的文件'ttxx' */
- fdd = open(".", O_RDONLY); /* 监视当前目录 */
- fcntl(fdd, F_SETSIG, SIGRTMIN);
- fcntl(fdd, F_NOTIFY, DN_MODIFY);
- while(1){
- while((n = read(fd, buf, 100)) > 0) /* 文件改变 */
- write(1, buf, n);
- pause();
- fcntl(fdd, F_NOTIFY, DN_MODIFY); /* 恢复监视 */
- }
-
- exit(0);
- }
复制代码
你可以试试,往ttxx里写东西马上就可以输出新写的文本,上面的“文件改变”有个问题,我这里是按上次读到的文件结尾开始向后读的,如果文件被截短了就会有错误,得不到新加的文本,应该再检查一下文件的长度,这个代码我就不加了,反正差不多就是这样了。 |
|