linux C完成一个线程,线程内同时实现检测test目录和btest目录内的文件创建和修改任务
时间: 2024-02-01 17:03:05 浏览: 33
可以使用Linux下的inotify机制来监测文件的创建和修改事件,同时使用多线程技术来实现检测test和btest目录内的文件创建和修改任务。
示例代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/inotify.h>
#include <pthread.h>
#define EVENT_SIZE (sizeof(struct inotify_event))
#define BUF_LEN (1024 * (EVENT_SIZE + 16))
void *watch_dir(void *dir_name) {
int fd, wd;
char buf[BUF_LEN];
fd = inotify_init();
if (fd == -1) {
perror("inotify_init");
exit(EXIT_FAILURE);
}
wd = inotify_add_watch(fd, (char *) dir_name, IN_CREATE | IN_MODIFY);
if (wd == -1) {
perror("inotify_add_watch");
exit(EXIT_FAILURE);
}
printf("Watching %s...\n", (char *) dir_name);
while (1) {
int len, i = 0;
len = read(fd, buf, BUF_LEN);
if (len == -1) {
perror("read");
exit(EXIT_FAILURE);
}
while (i < len) {
struct inotify_event *event = (struct inotify_event *) &buf[i];
if (event->mask & IN_CREATE) {
printf("File %s created in %s\n", event->name, (char *) dir_name);
}
if (event->mask & IN_MODIFY) {
printf("File %s modified in %s\n", event->name, (char *) dir_name);
}
i += EVENT_SIZE + event->len;
}
}
inotify_rm_watch(fd, wd);
close(fd);
}
int main() {
pthread_t thread1, thread2;
int rc1, rc2;
char *dir_name1 = "test";
char *dir_name2 = "btest";
rc1 = pthread_create(&thread1, NULL, watch_dir, (void *) dir_name1);
if (rc1) {
printf("Error: Unable to create thread1.\n");
exit(EXIT_FAILURE);
}
rc2 = pthread_create(&thread2, NULL, watch_dir, (void *) dir_name2);
if (rc2) {
printf("Error: Unable to create thread2.\n");
exit(EXIT_FAILURE);
}
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
```
上述代码中,使用`pthread_create`创建了两个线程,分别用于监测test和btest目录内的文件创建和修改事件。每个线程内部使用inotify机制监测目录,当有文件创建或修改事件时,输出相应的信息。
注意,在使用inotify机制时,需要先调用`inotify_init`函数创建一个inotify实例,然后调用`inotify_add_watch`函数添加监测目录,并指定监测的事件类型(IN_CREATE和IN_MODIFY)。当不再需要监测目录时,需要调用`inotify_rm_watch`函数移除监测。