Advertisement
Guest User

Untitled

a guest
May 6th, 2015
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <unistd.h>
  6. #include <stdlib.h>
  7. #include <err.h>
  8. #include <errno.h>
  9.  
  10. #define MAX_BUF 500
  11.  
  12. int main(int argc, char * argv[]) {
  13. (void)argc;
  14. (void)argv;
  15.  
  16. // Open a file
  17. int fd = open("asst2test.txt", O_RDWR | O_CREAT);
  18. if (fd < 0) {
  19. printf("Error opening asst2test.txt\n");
  20. }
  21.  
  22. // Write to file
  23. int r = write(fd, "test\n", strlen("test\n"));
  24. if (r != strlen("test\n")) {
  25. printf("Error writing, only wrote %d when expected %d\n", r, strlen("test\n"));
  26. }
  27.  
  28. // Dup file
  29. int dup_fd = dup2(fd, 5);
  30. if (dup_fd < 0) {
  31. printf("Error dup2\n");
  32. }
  33.  
  34. // Write from dup - should continue off where it last left off
  35. r = write(dup_fd, "test2\n", strlen("test2\n"));
  36. if (r != strlen("test2\n")) {
  37. printf("Error writing, only wrote %d when expected %d\n", r, strlen("test2\n"));
  38. }
  39.  
  40. // Set shared fp back to 0
  41. r = lseek(dup_fd, 0, SEEK_SET);
  42. if (r < 0) {
  43. printf("lseek failed\n");
  44. }
  45.  
  46. // Attempt to read from first fd
  47. char buf[MAX_BUF];
  48. int i = 0;
  49. do {
  50. printf("* attemping read of %d bytes\n", MAX_BUF -i);
  51. r = read(fd, &buf[i], MAX_BUF - i);
  52. printf("* read %d bytes\n", r);
  53. i += r;
  54. } while (i < MAX_BUF && r > 0);
  55. printf("We read:\n%s", buf);
  56.  
  57. // Close dup'd fd and reset fp to 0
  58. close(dup_fd);
  59. lseek(fd, 0, SEEK_SET);
  60.  
  61. // Reading from original fd should still work
  62. i = 0;
  63. do {
  64. printf("* attemping read of %d bytes\n", MAX_BUF -i);
  65. r = read(fd, &buf[i], MAX_BUF - i);
  66. printf("* read %d bytes\n", r);
  67. i += r;
  68. } while (i < MAX_BUF && r > 0);
  69. printf("We read:\n%s", buf);
  70.  
  71. // Dup the fd again, onto the same value as before
  72. dup_fd = dup2(fd, 5);
  73. if (dup_fd < 0) {
  74. printf("Error dup2 2\n");
  75. }
  76.  
  77. // Reset fp to 0 using original fd, then close original fd
  78. lseek(fd, 0, SEEK_SET);
  79. close(fd);
  80.  
  81. // Attempt to read from the dup'd fd - should work
  82. i = 0;
  83. do {
  84. printf("* attemping read of %d bytes\n", MAX_BUF -i);
  85. r = read(dup_fd, &buf[i], MAX_BUF - i);
  86. printf("* read %d bytes\n", r);
  87. i += r;
  88. } while (i < MAX_BUF && r > 0);
  89. printf("We read:\n%s", buf);
  90.  
  91. return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement