【发布时间】:2019-08-21 23:22:21
【问题描述】:
我的任务是制作一个分析文件/目录并提供有关它们的信息的程序。您可以设置递归标志来分析每个子目录。每个目录都由一个新进程分析(这是项目的要求),我想在每次找到新文件(SIGUSR2)或目录(SIGUSR1)时发送一个信号。在这些信号的处理程序中,我想增加跟踪程序找到的文件/目录数量的全局变量。我在使不同的进程增加相同的全局变量时遇到问题。我已经尝试过管道,但我似乎无法让它工作。
这是我分析目录的函数:
void process_dir(const ProgramConfig program_config, const char *dname, FILE *outstream)
{
raise(SIGUSR1);
/* Create a new process */
pid_t pid = fork();
if (pid == 0)
{
/* Child process */
struct dirent *ent;
DIR *dir;
/* Open directory */
if ((dir = opendir(dname)) != NULL)
{
/* Go through each file in this directory */
while ((ent = readdir(dir)) != NULL)
{
/* Ignore anything that isn't a file or a directory */
if (ent->d_type != DT_DIR && ent->d_type != DT_REG)
continue;
/* Ignore the '.' and '..' directories */
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
continue;
/* Prepend this directory name to file name */
char name[256];
strcpy(name, dname);
strcat(name, "/");
strcat(name, ent->d_name);
if (ent->d_type == DT_DIR && program_config.r_flag)
{
/* Found a subdirectory, process it if -r flag enabled */
process_dir(program_config, name, outstream);
}
else
{
/* Found a file, process it */
process_file(program_config, name, outstream);
}
}
}
else
{
/* Error opening directory */
}
/* Exit from child process */
exit(0);
}
else if (pid < 0)
{
/* Error creating process */
}
else
{
/* Parent process */
wait(NULL);
/* Log this event */
if (program_config.v_flag)
{
char act[100];
sprintf(act, "PROCESSED DIR %s", dname);
log_event(act);
}
}
}
这是我的处理程序:
void sigusr1_handler(int sig)
{
if (sig != SIGUSR1)
{
fprintf(stderr, "Wrong signal received! Expected: SIGUSR1\n");
}
dirsFound++;
printf("New directory: %ld/%ld directories/files at this time.\n", dirsFound, filesFound);
}
void sigusr2_handler(int sig)
{
if (sig != SIGUSR2)
{
fprintf(stderr, "Wrong signal received! Expected: SIGUSR2\n");
}
filesFound++;
}
使用线程不是此分配的选项。
【问题讨论】:
-
您可能会发现在这里线程是比进程更实用的解决方案。
-
我知道,我现在一直在学习线程。我忘了补充一点,这个项目的要求之一是为每个目录使用各种进程。所以线程不在等式中。
-
同时使用来自多个线程或进程的同一个磁盘似乎是一个巨大的潜在性能问题......这就像家庭作业还是什么? :)
-
是的,这是一个 uni 项目。
-
好吧,尽管这可能是不明智的,但这可以通过一个共享内存映射文件和原子增量来解决......或者查看“kill”函数以向父级发送信号过程。
标签: c unix recursion fork posix