Reading and Writing Files (OS Perspective)
Reading and Writing Files (OS Perspective)
🔷 1. Basic Idea
Once a file is created, the OS provides system calls to:
-
Read data from a file
-
Write data to a file
👉 These operations are typically sequential:
-
Data is processed from beginning to end, byte by byte
2. Reading Files Sequentially
🔷 Example Flow (cat foo)
When you run:
The OS performs the following steps:
🔹 Step 1: Open the File
-
Opens file in read-only mode
-
Returns a file descriptor (fd)
👉 Example:
🔹 Why fd = 3?
Because:
-
0→ Standard Input -
1→ Standard Output -
2→ Standard Error
👉 First available descriptor = 3
🔹 Step 2: Read Data
-
fd→ which file -
buffer→ where data is stored -
size→ how much to read
👉 Example:
-
Reads 6 bytes
-
Includes newline
\n
🔹 Step 3: Write to Output
-
1= standard output (screen)
👉 Displays:
🔹 Step 4: Repeat Until EOF
👉 Return value 0 = End of File (EOF)
🔹 Step 5: Close File
👉 Releases file descriptor
Sequential Reading Summary
👉 Data is read in order, not randomly
3. Writing Files Sequentially
🔷 Steps
-
Open file for writing:
-
Write data:
-
Repeat if needed
-
Close file:
Sequential Writing Flow
👉 Data is written continuously in sequence
4. What is strace?
🔷 Definition
strace is a system call tracing tool.
👉 It shows:
-
What system calls a program makes
-
Arguments passed
-
Return values
🔷 Why is it Useful?
-
Understand OS behavior
-
Debug programs
-
Learn how programs interact with kernel
🔷 Example
Output (simplified):
5. Key Observations from strace
🔹 1. Everything is a system call
-
File operations go through OS
🔹 2. File descriptor usage
-
Identifies which file is accessed
🔹 3. Sequential behavior
-
Repeated
read()calls until EOF
🔹 4. Output handling
-
write()to fd = 1 → screen
6. Important Concepts
🔷 End of File (EOF)
-
read()returns 0 -
Indicates no more data
🔷 Buffering
-
Data is read in chunks (e.g., 4KB)
-
Improves efficiency
🔷 Abstraction
-
User sees simple commands (
cat) -
OS handles complexity internally
7. Key Takeaways
-
Reading:
-
Writing:
-
File descriptor:
-
0 → input
-
1 → output
-
2 → error
-
-
strace:-
Tracks system calls
-
Helps understand OS internals
-
-
Minimal seek operations
-
Continuous data flow
👉 strace reveals:
How high-level programs interact with the OS at a low level
Comments
Post a Comment