Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <stdio.h>
- #include <string.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <err.h>
- #include <errno.h>
- #define MAX_BUF 500
- int main(int argc, char * argv[]) {
- (void)argc;
- (void)argv;
- // Open a file
- int fd = open("asst2test.txt", O_RDWR | O_CREAT);
- if (fd < 0) {
- printf("Error opening asst2test.txt\n");
- }
- // Write to file
- int r = write(fd, "test\n", strlen("test\n"));
- if (r != strlen("test\n")) {
- printf("Error writing, only wrote %d when expected %d\n", r, strlen("test\n"));
- }
- // Dup file
- int dup_fd = dup2(fd, 5);
- if (dup_fd < 0) {
- printf("Error dup2\n");
- }
- // Write from dup - should continue off where it last left off
- r = write(dup_fd, "test2\n", strlen("test2\n"));
- if (r != strlen("test2\n")) {
- printf("Error writing, only wrote %d when expected %d\n", r, strlen("test2\n"));
- }
- // Set shared fp back to 0
- r = lseek(dup_fd, 0, SEEK_SET);
- if (r < 0) {
- printf("lseek failed\n");
- }
- // Attempt to read from first fd
- char buf[MAX_BUF];
- int i = 0;
- do {
- printf("* attemping read of %d bytes\n", MAX_BUF -i);
- r = read(fd, &buf[i], MAX_BUF - i);
- printf("* read %d bytes\n", r);
- i += r;
- } while (i < MAX_BUF && r > 0);
- printf("We read:\n%s", buf);
- // Close dup'd fd and reset fp to 0
- close(dup_fd);
- lseek(fd, 0, SEEK_SET);
- // Reading from original fd should still work
- i = 0;
- do {
- printf("* attemping read of %d bytes\n", MAX_BUF -i);
- r = read(fd, &buf[i], MAX_BUF - i);
- printf("* read %d bytes\n", r);
- i += r;
- } while (i < MAX_BUF && r > 0);
- printf("We read:\n%s", buf);
- // Dup the fd again, onto the same value as before
- dup_fd = dup2(fd, 5);
- if (dup_fd < 0) {
- printf("Error dup2 2\n");
- }
- // Reset fp to 0 using original fd, then close original fd
- lseek(fd, 0, SEEK_SET);
- close(fd);
- // Attempt to read from the dup'd fd - should work
- i = 0;
- do {
- printf("* attemping read of %d bytes\n", MAX_BUF -i);
- r = read(dup_fd, &buf[i], MAX_BUF - i);
- printf("* read %d bytes\n", r);
- i += r;
- } while (i < MAX_BUF && r > 0);
- printf("We read:\n%s", buf);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement