| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- #include <stdio.h>
- #include <unistd.h>
- #include <string.h>
- #include <sys/stat.h>
- #define MAX_ATTEMPTS 5 // Maximum retry attempts
- int main(int argc, char *argv[]) {
- if (argc < 3) {
- fprintf(stderr, "Usage: %s <target_file> \"text to append\"\n", argv[0]);
- return 1;
- }
- char *target_file = argv[1];
- char *text_to_append = argv[2];
- char lock_file[256];
- // Generate lock file name
- snprintf(lock_file, sizeof(lock_file), "%s.LCK", target_file);
- // Check if the target file exists; if not, create it
- struct stat buffer;
- if (stat(target_file, &buffer) != 0) {
- // File does not exist, create it
- printf("Target file does not exist. Creating %s...\n", target_file);
- FILE *file = fopen(target_file, "w");
- if (!file) {
- perror("Error creating file");
- return 1;
- }
- fclose(file);
- }
- int attempts = 0;
- while (attempts < MAX_ATTEMPTS) {
- if (link(target_file, lock_file) == 0) {
- // Link created successfully
- printf("Lock acquired: %s\n", lock_file);
- FILE *file = fopen(target_file, "a");
- if (file) {
- fprintf(file, "%s\n", text_to_append);
- fclose(file);
- printf("Text appended to %s\n", target_file);
- } else {
- perror("fopen");
- }
- // used for debugging
- // sleep(5);
- unlink(lock_file);
- // Remove the lock
- printf("Lock released: %s\n", lock_file);
- return 0;
- } else {
- perror("link");
- sleep(1);
- attempts++;
- }
- }
- printf("Failed to acquire lock after %d attempts.\n", MAX_ATTEMPTS);
- return 1;
- }
|