I was tasked with making a program that analyzes a file/directory and gives information about them. You can set a recursion flag to analyze every subdirectory. Every directory is analyzed by a new process (this is a requirement of the project) and I want to send a signal every time a new file (SIGUSR2) or directory (SIGUSR1) is found. In the handler for those signals I want to increment global variables that keep track of the number of files/directories found by the program. I'm having problems with making the different processes increment the same global variable. I've tried pipes but I can't seem to get it to work.
Here is my function that analyzes a directory:
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);
}
}
}
Here are my handlers:
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++;
}
Using threads is not an option for this assignment.