【发布时间】:2021-04-09 09:45:28
【问题描述】:
我正在研究文件监控系统项目,其中首先将所有数据复制到目标文件夹,然后它应该监控源文件夹和目标文件夹中的数据。但不幸的是,它只是监控源文件夹中的数据。
我将 inotify 功能 分为两部分,因为我使用inotifyFunc1 来帮助我先复制文件夹。复制数据后,我使用inotifyFunc2 监控两个文件夹中的数据。但正如我所说,它只是监视第一个 源文件夹。
这段代码很大,但我不知道如何简短地理解它。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#define STRING_LEN 200
#define MAX_EVENTS 1024
#define NAME_LEN 16
#define EVENT_SIZE (sizeof(struct inotify_event))
#define BUFFER_LEN (MAX_EVENTS * (EVENT_SIZE + NAME_LEN))
typedef struct{
int fd, wd, result, length;
uint32_t mask[2];
char path1[STRING_LEN], path2[STRING_LEN], cmd[STRING_LEN], option, buffer[BUFFER_LEN];
} monitoring;
monitoring monitor;
void sig_handler(int signal){
printf("\nThe program is closed\n");
inotify_rm_watch(monitor.fd, monitor.wd);
close(monitor.fd);
exit(0);
}
void inotifyFunc1(char *path1, uint32_t *maskPtr1){
monitor.fd = inotify_init();
if(fcntl(monitor.fd, F_SETFL, O_NONBLOCK)){
perror("inotify not initialized: ");
exit(0);
}
monitor.wd = inotify_add_watch(monitor.fd, path1, *maskPtr1);
if(monitor.wd < 0){
perror("Sorry");
exit(1);
}
}
void inotifyFunc2(char *path2, uint32_t *maskPtr2)
{
while(1)
{
int i = 0;
monitor.length = read(monitor.fd, monitor.buffer, BUFFER_LEN);
while(i<monitor.length){
struct inotify_event *event = (struct inotify_event *)&monitor.buffer[i];
if(event->len){
if(event->mask & *maskPtr2){
if(event->mask & IN_ISDIR){
printf("Directory is created\n");
break;
}
else{
printf("File is created\n");
break;
}
}
}
}
}
}
void monitoringSystem(char *pathname1, char *pathname2)
{
/* Closing inotify */
signal(SIGINT,sig_handler);
do
{
printf("Choose the source path: ");
scanf("%s", pathname1);
monitor.mask[0] = ENOENT;
inotifyFunc1(pathname1, &monitor.mask[0]);
printf("Choose the destination path: ");
scanf("%s", pathname2);
inotifyFunc1(pathname2, &monitor.mask[0]);
monitor.result = strcmp(pathname1, pathname2);
if(monitor.result == 0){
printf("Error: Both locations are the same\n");
exit(3);
}
else{
sprintf(monitor.cmd, "cp -r %s %s", pathname1, pathname2);
system(monitor.cmd);
printf("Data is copied from source to destination\n");
}
printf("\nBoth locations are being monitored\n");
monitor.mask[1] = IN_CREATE;
inotifyFunc1(pathname1, &monitor.mask[1]);
inotifyFunc2(pathname1, &monitor.mask[1]);
inotifyFunc1(pathname2, &monitor.mask[1]);
inotifyFunc2(pathname2, &monitor.mask[1]);
printf("Do you want to give location again? [y/n]: ");
scanf("%s", &monitor.option);
} while(monitor.option == 'y');
}
int main(int argc, char *argv[])
{
printf("DATA RECOVERY SYSTEM\n");
printf("WELCOME TO THE MAIN MENU\n\n");
monitoringSystem(monitor.path1, monitor.path2);
return 0;
}
【问题讨论】:
-
你能解释一下你是如何测试这个的吗?你想要直到它输出“两个位置都被监控”然后做点什么吗?如果没有,你的程序是什么?如果是这样,您在看到该消息后在做什么,您期望发生什么,会发生什么?