12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- /*
- After each of the calls to write() in the following code, explain what the content of
- the output file would be, and why:
- fd1 = open(file, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
- fd2 = dup(fd1);
- fd3 = open(file, O_RDWR);
- write(fd1, "Hello,", 6);
- write(fd2, "world", 6);
- lseek(fd2, 0, SEEK_SET);
- write(fd1, "HELLO,", 6);
- write(fd3, "Gidday", 6);
- */
- #include <stdlib.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <assert.h>
- #include <stdio.h>
- int
- main (int argc, char *argv[])
- {
- if (argc != 2) return EXIT_FAILURE;
- int fd1, fd2, fd3;
- fd1 = open (argv[1], O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
- fd2 = dup (fd1);
- fd3 = open (argv[1], O_RDWR);
- write (fd1, "Hello,", 6);
- // Hello,
- write (fd2, "world", 6);
- // Hello,world?
- printf ("lseek %lld\n", lseek (fd2, 0, SEEK_CUR));
- lseek (fd2, 0, SEEK_SET);
- write (fd1, "HELLO,", 6);
- // HELLO,world?
- assert (lseek (fd1, 0, SEEK_CUR) != lseek (fd3, 0, SEEK_CUR));
- // lseek for dup and opened fd1 == fd2, where fd3 is still 0
- write (fd3, "Gidday", 6);
- // Giddayworld?
- return EXIT_SUCCESS;
- }
|