exercise_5_6.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /*
  2. After each of the calls to write() in the following code, explain what the content of
  3. the output file would be, and why:
  4. fd1 = open(file, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
  5. fd2 = dup(fd1);
  6. fd3 = open(file, O_RDWR);
  7. write(fd1, "Hello,", 6);
  8. write(fd2, "world", 6);
  9. lseek(fd2, 0, SEEK_SET);
  10. write(fd1, "HELLO,", 6);
  11. write(fd3, "Gidday", 6);
  12. */
  13. #include <stdlib.h>
  14. #include <unistd.h>
  15. #include <fcntl.h>
  16. #include <assert.h>
  17. #include <stdio.h>
  18. int
  19. main (int argc, char *argv[])
  20. {
  21. if (argc != 2) return EXIT_FAILURE;
  22. int fd1, fd2, fd3;
  23. fd1 = open (argv[1], O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
  24. fd2 = dup (fd1);
  25. fd3 = open (argv[1], O_RDWR);
  26. write (fd1, "Hello,", 6);
  27. // Hello,
  28. write (fd2, "world", 6);
  29. // Hello,world?
  30. printf ("lseek %lld\n", lseek (fd2, 0, SEEK_CUR));
  31. lseek (fd2, 0, SEEK_SET);
  32. write (fd1, "HELLO,", 6);
  33. // HELLO,world?
  34. assert (lseek (fd1, 0, SEEK_CUR) != lseek (fd3, 0, SEEK_CUR));
  35. // lseek for dup and opened fd1 == fd2, where fd3 is still 0
  36. write (fd3, "Gidday", 6);
  37. // Giddayworld?
  38. return EXIT_SUCCESS;
  39. }