Skip to content

Instantly share code, notes, and snippets.

@josephok
Created January 5, 2015 14:06
Show Gist options
  • Select an option

  • Save josephok/f478dde7c369bc8a8fae to your computer and use it in GitHub Desktop.

Select an option

Save josephok/f478dde7c369bc8a8fae to your computer and use it in GitHub Desktop.
The Linux Programming Interface Exercise 5-6
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);
Content is:
Gidday\00world\00
fd1 and fd2 share the same file offset, fd3 opens with offset 0 from SEEK_SET
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
int fd1, fd2, fd3;
fd1 = open("test.txt", O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
fd2 = dup(fd1);
fd3 = open("test.txt", O_RDWR);
write(fd1, "Hello,", sizeof("Hello,"));
write(fd2, "world", sizeof("world"));
lseek(fd2, 0, SEEK_SET);
write(fd1, "HELLO,", 6);
write(fd3, "Gidday", 6);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment