File system calls
System call and library function, open and its flags, read, write, lseek, close, descriptors 0, 1 and 2, the return value, errno and perror.
- 29 cards
- 4 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
A few cards from the deck
System call: what is it?
Show the answer
A program's request to the kernel for an operation it may not do alone, such as reading a file; the processor switches from user mode to kernel mode while it is handled.
This switch has a cost, hence library functions such as fread or printf that gather data in a buffer and only call read or write when worthwhile.
The file
t.txtcontainsABCDEF. What does it contain after this program?
```c
int fd = open("t.txt", O_RDWR);
lseek(fd, 2, SEEK_SET);
write(fd, "xy", 2);
close(fd);`ABxyEFABxyCDEFxyCDEFABCDEFxy
Show the answer
ABxyEFlseek sets the position at byte 2; write overwrites the next two bytes (C and D) without shifting anything. The file keeps its size of 6 bytes. Writing at the end would need SEEK_END or O_APPEND.
At the end of the file, read returns …; on error, it returns … and sets errno.
Show the answer
At the end of the file, read returns 0; on error, it returns -1 and sets errno.
Mixing them up is a classic mistake: 0 is not an error, it is the normal stop signal for a read loop.
File descriptor: what is it?
Show the answer
A small integer, specific to each process, that designates an open file, a pipe, a socket or a terminal for the read, write and close calls.
It is an index into a per-process table. The first three entries are open at startup: 0 standard input, 1 standard output, 2 standard error.
A program opens a file with open then calls write(fd, "ok", 2) without testing open's return. When the file is missing, the output shows
write: Bad file descriptor. What is the cause and the fix?- write has too few bytes to write: increase its size
- The file is not closed: add a close before the write
- errno was reset to zero: read it again before the write
- open returned -1, an invalid descriptor for write: test fd == -1 right after open
Show the answer
open returned -1, an invalid descriptor for write: test fd == -1 right after open
The real fault is upstream: open failed (“No such file or directory”) and returned -1, which the program passed to write, which complained. Fixing the write would only hide the error; test open's return, print perror and exit.