Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Powtórz zadanie trzecie używając fcntl() i blokując wybrane fragmenty pliku.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <string.h>
- #define BUFFER_SIZE 128
- int main(int argc, char *argv[])
- {
- char *filename = (char *)malloc(sizeof(strlen(argv[0]) + strlen(".c") + 1));
- filename = strcat(argv[0], ".c");
- int first_fd, second_fd;
- char buffer[BUFFER_SIZE];
- int result;
- struct flock file_lock;
- if((first_fd = open(filename, O_RDONLY | 0600)) == -1) {
- perror("open");
- return EXIT_FAILURE;
- }
- if((second_fd = fcntl(first_fd, F_DUPFD)) == -1) {
- perror("fcntl_1");
- return EXIT_FAILURE;
- }
- file_lock.l_type = F_RDLCK;
- file_lock.l_whence = SEEK_SET;
- file_lock.l_start = 16;
- file_lock.l_len = 64;
- if(fcntl(second_fd, F_SETLKW, &file_lock) == -1) {
- perror("fcntl_2");
- return EXIT_FAILURE;
- }
- printf("Odczytywanie pliku za pomoca skopiowanego deskryptora: \n");
- for(;;) {
- memset(buffer, '\0', BUFFER_SIZE);
- result = read(second_fd, buffer, BUFFER_SIZE-1);
- if(result == -1) {
- perror("read");
- return EXIT_FAILURE;
- }
- else if(result == 0)
- break;
- else
- printf("%s", buffer);
- }
- printf("\n");
- file_lock.l_type = F_UNLCK;
- if(fcntl(second_fd, F_SETLK, &file_lock) == -1) {
- perror("fnctl_3");
- return EXIT_FAILURE;
- }
- if(close(first_fd) || close(second_fd)) {
- perror("close");
- return EXIT_FAILURE;
- }
- return EXIT_SUCCESS;
- }
Add Comment
Please, Sign In to add comment