#include #include #include #include #include #include #include int Debug = 0; char *source_dir, *dest_dir; time_t now; void RenameJob(char *fname) { char buf[256]; /* We first move the data file, this eases locking stuff */ fname[0] = 'd'; sprintf(buf, "%s/%s", dest_dir, fname); /* Does the dest file exist ? */ if (access(buf, F_OK) == 0) { fprintf(stderr, "Destination %s already exists, skipping\n", fname); return; } if (Debug) fprintf(stderr, "Will rename %s to %s\n", fname, buf); rename(fname, buf); /* The we move the queue file, the lock will stay until released */ fname[0] = 'q'; sprintf(buf, "%s/%s", dest_dir, fname); if (access(buf, F_OK) == 0) { fprintf(stderr, "Destination %s already exists, skipping\n", fname); return; } if (Debug) fprintf(stderr, "Will rename %s to %s\n", fname, buf); rename(fname, buf); } void CheckFile(char *fname, time_t delay) { char buf[256]; FILE *f; time_t t; if ((f = fopen(fname, "r+")) == NULL) { fprintf(stderr, "Can't read %s: %s\n", fname, strerror(errno)); return; } if (flock(fileno(f), LOCK_EX|LOCK_NB) == -1) { if (errno == EWOULDBLOCK) { if (Debug) fprintf(stderr, "%s already locked\n", fname); } else { fprintf(stderr, "Could not lock %s: %s\n", fname, strerror(errno)); } fclose(f); return; } /* Get the job creation time */ while (fgets(buf, sizeof buf, f) != NULL) { if (buf[0] == 'T') { t = atol(buf + 1); break; } } if (Debug) fprintf(stderr, "Age is : %ld (limit %ld)\n", now - t, delay); /* If the time is zero we did not find the T line, ignore the job */ if (t > 0 && (t < (now - delay))) { RenameJob(fname); } fclose(f); } void Usage(char *prog) { fprintf(stderr, "Usage: %s source_dir dest_dir hours_age\n", prog); exit(1); } void main(int argn, char *argv[]) { DIR *dir; struct dirent *d; struct stat st; time_t delay; /* Check the number of arguments */ if (argn != 4) Usage(argv[0]); source_dir = argv[1]; dest_dir = argv[2]; delay = atol(argv[3]) * 3600; time(&now); /* Go to the source directory */ if (chdir(source_dir) == -1) { fprintf(stderr, "Can't change directory to %s: %s\n", source_dir, strerror(errno)); exit(1); } /* Are we authorized to write the destination directory ? */ if (access(dest_dir, R_OK | W_OK | X_OK) == -1) { fprintf(stderr, "Can't access %s: %s\n", dest_dir, strerror(errno)); exit(1); } /* Parse the source directory, we only work with the qf file */ if ((dir = opendir(".")) == NULL) { fprintf(stderr, "Can't open %s: %s\n", dest_dir, strerror(errno)); exit(1); } while ((d = readdir(dir)) != NULL) { if (d->d_reclen < 2 || d->d_name[0] != 'q' || d->d_name[1] != 'f') continue; if (Debug) fprintf(stderr, "Handling %s ", d->d_name); CheckFile(d->d_name, delay); } closedir(dir); exit(0); }