#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> int main() { int fd1, fd2; char c; fd1 = open("foobar.txt", O_RDONLY); fd2 = open("foobar.txt", O_RDONLY); read(fd2, &c, 1); read(fd2, &c, 1); read(fd2, &c, 1); read(fd2, &c, 1); printf("c = %c\n", c); //read(fd2, &c, 1); // dup2(fd2, fd1); read(fd1, &c, 1); dup2(fd1, fd2); read(fd2, &c, 1); printf("c = %c\n", c); exit(0); }
> gcc one.c && ./a.out c = b c = o
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #define STR_LEN 6 int main() { int fd1; fd1 = open("foobar.txt", O_RDONLY); if (dup2(fd1, STDIN_FILENO) < 0) { printf("Unable to duplicate file descriptor."); exit(EXIT_FAILURE); } char *c1 = (char*)malloc(STR_LEN); char *c2 = (char*)malloc(STR_LEN); scanf("%s %s", c1, c2); printf("c1 = %s\nc2 = %s\n", c1, c2); // SAVE THE WHALES, FREE THE MALLOCS free(c1); free(c2); exit(0); }
> gcc three.c&& ./a.out c1 = foobar c2 = test