lockingappend.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <string.h>
  4. #include <sys/stat.h>
  5. #define MAX_ATTEMPTS 5 // Maximum retry attempts
  6. int main(int argc, char *argv[]) {
  7. if (argc < 3) {
  8. fprintf(stderr, "Usage: %s <target_file> \"text to append\"\n", argv[0]);
  9. return 1;
  10. }
  11. char *target_file = argv[1];
  12. char *text_to_append = argv[2];
  13. char lock_file[256];
  14. // Generate lock file name
  15. snprintf(lock_file, sizeof(lock_file), "%s.LCK", target_file);
  16. // Check if the target file exists; if not, create it
  17. struct stat buffer;
  18. if (stat(target_file, &buffer) != 0) {
  19. // File does not exist, create it
  20. printf("Target file does not exist. Creating %s...\n", target_file);
  21. FILE *file = fopen(target_file, "w");
  22. if (!file) {
  23. perror("Error creating file");
  24. return 1;
  25. }
  26. fclose(file);
  27. }
  28. int attempts = 0;
  29. while (attempts < MAX_ATTEMPTS) {
  30. if (link(target_file, lock_file) == 0) {
  31. // Link created successfully
  32. printf("Lock acquired: %s\n", lock_file);
  33. FILE *file = fopen(target_file, "a");
  34. if (file) {
  35. fprintf(file, "%s\n", text_to_append);
  36. fclose(file);
  37. printf("Text appended to %s\n", target_file);
  38. } else {
  39. perror("fopen");
  40. }
  41. // used for debugging
  42. // sleep(5);
  43. unlink(lock_file);
  44. // Remove the lock
  45. printf("Lock released: %s\n", lock_file);
  46. return 0;
  47. } else {
  48. perror("link");
  49. sleep(1);
  50. attempts++;
  51. }
  52. }
  53. printf("Failed to acquire lock after %d attempts.\n", MAX_ATTEMPTS);
  54. return 1;
  55. }