Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Zademonstruj działanie funkcji replikującej deskryptory plików.
- */
- #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;
- if((first_fd = open(filename, O_RDONLY | 0600)) == -1) {
- perror("open");
- return EXIT_FAILURE;
- }
- if((second_fd = dup(first_fd)) == -1) {
- perror("dup2");
- 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");
- if(close(first_fd) || close(second_fd)) {
- perror("close");
- return EXIT_FAILURE;
- }
- return EXIT_SUCCESS;
- }
Add Comment
Please, Sign In to add comment