Tobiahao

S01_PLIKI_05

Jan 20th, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.51 KB | None | 0 0
  1. /*
  2. Powtórz zadanie trzecie używając fcntl() i blokując wybrane fragmenty pliku.
  3. */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <fcntl.h>
  10. #include <unistd.h>
  11. #include <string.h>
  12.  
  13. #define BUFFER_SIZE 128
  14.  
  15. int main(int argc, char *argv[])
  16. {
  17.     char *filename = (char *)malloc(sizeof(strlen(argv[0]) + strlen(".c") + 1));
  18.     filename = strcat(argv[0], ".c");
  19.  
  20.     int first_fd, second_fd;
  21.     char buffer[BUFFER_SIZE];
  22.     int result;
  23.     struct flock file_lock;
  24.  
  25.     if((first_fd = open(filename, O_RDONLY | 0600)) == -1) {
  26.         perror("open");
  27.         return EXIT_FAILURE;
  28.     }
  29.  
  30.     if((second_fd = fcntl(first_fd, F_DUPFD)) == -1) {
  31.         perror("fcntl_1");
  32.         return EXIT_FAILURE;
  33.     }
  34.  
  35.     file_lock.l_type = F_RDLCK;
  36.     file_lock.l_whence = SEEK_SET;
  37.     file_lock.l_start = 16;
  38.     file_lock.l_len = 64;
  39.  
  40.     if(fcntl(second_fd, F_SETLKW, &file_lock) == -1) {
  41.         perror("fcntl_2");
  42.         return EXIT_FAILURE;
  43.     }
  44.  
  45.     printf("Odczytywanie pliku za pomoca skopiowanego deskryptora: \n");
  46.  
  47.     for(;;) {
  48.         memset(buffer, '\0', BUFFER_SIZE);
  49.         result = read(second_fd, buffer, BUFFER_SIZE-1);
  50.         if(result == -1) {
  51.             perror("read");
  52.             return EXIT_FAILURE;
  53.         }
  54.         else if(result == 0)
  55.             break;
  56.         else
  57.             printf("%s", buffer);
  58.     }
  59.  
  60.     printf("\n");
  61.  
  62.     file_lock.l_type = F_UNLCK;
  63.  
  64.     if(fcntl(second_fd, F_SETLK, &file_lock) == -1) {
  65.         perror("fnctl_3");
  66.         return EXIT_FAILURE;
  67.     }
  68.  
  69.     if(close(first_fd) || close(second_fd)) {
  70.         perror("close");
  71.         return EXIT_FAILURE;
  72.     }
  73.  
  74.     return EXIT_SUCCESS;
  75. }
Add Comment
Please, Sign In to add comment