0% found this document useful (0 votes)
7 views21 pages

Module 4 - Upto File Access Methods

The document explains the interaction methods between the CPU and I/O devices, focusing on Programmed I/O, Interrupt-Driven I/O, and Direct Memory Access (DMA). It highlights the inefficiencies of Programmed I/O due to CPU busy waiting and the advantages of Interrupt-Driven I/O and DMA in improving system performance. Additionally, it discusses the role of device drivers in facilitating communication between the operating system and hardware devices.

Uploaded by

aaronageorge64
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views21 pages

Module 4 - Upto File Access Methods

The document explains the interaction methods between the CPU and I/O devices, focusing on Programmed I/O, Interrupt-Driven I/O, and Direct Memory Access (DMA). It highlights the inefficiencies of Programmed I/O due to CPU busy waiting and the advantages of Interrupt-Driven I/O and DMA in improving system performance. Additionally, it discusses the role of device drivers in facilitating communication between the operating system and hardware devices.

Uploaded by

aaronageorge64
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

I/O system

The CPU communicates with I/O devices through special hardware registers located in the
device controller.
Each device controller which is a hardware component integrated in the mother board
chipset- typically has control, status, and data registers.
When the CPU wants to perform an operation, it first issues a command by writing to the
device’s control register, specifying whether it wants to read or write.
In a write operation, the CPU places the data into the device’s data register and then sets the
appropriate control bits to start the transfer.
In a read operation, the CPU checks the device’s status register to determine whether data is
available; once the device indicates it is ready, the CPU reads the data from the data register.
There are two common ways the CPU manages this interaction.
 In programmed I/O (polling), the CPU repeatedly checks the status register in a loop
until the device becomes ready, which wastes CPU time.
 In interrupt-driven I/O, the CPU issues the command and continues executing other
tasks. When the device completes the operation or becomes ready, it sends an
interrupt signal. The CPU then temporarily stops its

The Canonical Protocol Interface Internals In the picture above, the (simplified) device
interface is comprised of three registers: a status register, which can be read to see the current
status of the device; a command register, to tell the device to perform a certain task; and a
data register to pass data to the device, or get data from the device. By reading and writing
these registers, the operating system can control device behavior.
The protocol has four steps.
In the first, the OS waits until the device is ready to receive a command by repeatedly
reading the status register; we call this polling the device (basically, just asking it what is
going on).
Second, the OS sends some data down to the data register; one can imagine that if this were a
disk, for example, that multiple writes would need to take place to transfer a disk block (say
4KB) to the device.
When the main CPU is involved with the data movement (as in this example protocol), we refer
to it as programmed I/O (PIO). Programmed I/O (PIO) is a data transfer method in which the
CPU is responsible for moving data between the I/O device and main memory. In PIO, the CPU
executes instructions to read from or write to the device’s data register. This means the CPU
directly handles every data transfer operation. The steps involves
 CPU writes command to Control Register.
 CPU repeatedly checks Status Register (polling).
 When device is ready, CPU reads/writes data through Data Register.
 CPU handles every byte/word transfer.

Third, the OS writes a command to the command register; doing so implicitly lets the device
know that both the data is present and that it should begin working on the command.
Finally, the OS waits for the device to finish by again polling it in a loop, waiting to see if it
is finished (it may then get an error code to indicate success or failure).

Polling / Busy waiting


Polling is a method used by the CPU to check the status of an I/O device repeatedly until the
device is ready to perform an operation. In this technique, the CPU continuously reads the
device’s status register in a loop to determine whether the device is busy or ready.
If the device is not ready, the CPU keeps checking again and again without performing any
other useful work. Once the device becomes ready, the CPU proceeds with the data transfer.
Although polling is simple to implement, it is inefficient because it wastes CPU time in busy
waiting, especially when the device is slow.

Disadvantage of Programming I/O


The main disadvantage is that it wastes CPU time. In programmed I/O, the CPU is responsible
for both checking the device status (usually by polling) and transferring each byte or word of
data. While the device is busy, the CPU repeatedly checks the status register in a loop. This is
called busy waiting, and during this time the CPU cannot perform other useful tasks.
Another disadvantage is low efficiency for large data transfers. Since the CPU handles every
data movement between the device and memory, the transfer speed is limited by CPU speed.
This increases CPU overhead and reduces overall system performance.
Programmed I/O also reduces system throughput, especially when dealing with slow devices
like disks or printers. The CPU becomes tied up with I/O operations instead of executing other
processes.
Because of these disadvantages, modern systems prefer interrupt-driven I/O or Direct
Memory Access (DMA), which reduce CPU involvement and improve performance.
Interrupt Driven I/O
An interrupt is a signal sent by a hardware device to the CPU to indicate that it needs attention.
In interrupt-driven I/O, instead of continuously checking (polling) whether a device is ready,
the CPU issues an I/O request and continues executing other instructions. When the device
completes its operation or becomes ready, it sends an interrupt signal to the CPU. The CPU
temporarily stops its current execution and transfers control to a special routine called the
Interrupt Service Routine (ISR).
The ISR is a small piece of kernel code designed to handle the specific interrupt, such as
reading data from a device register or acknowledging completion of an operation.

For example, when a process is executing and it needs to read data from the disk, it makes a
system call (like read). The operating system then sends a command to the disk controller and
the process is usually put into a waiting (blocked) state. The CPU is free to execute another
process while the disk performs the read Once the disk finishes reading the required data into
its buffer (or into memory via DMA), it sends an interrupt to the CPU.
The CPU completes its current instruction, saves the context of the running process (such as
registers and program counter), and jumps to the disk’s ISR using the interrupt vector table.
The ISR checks the device status, transfers data if necessary, updates kernel data structures,
and marks the waiting process as ready. After the ISR finishes, the CPU restores the previous
context and resumes execution of the interrupted process or schedules another ready process.
Thus, interrupt-driven I/O improves efficiency because the CPU does not waste time waiting
for slow devices like disks. The ISR plays a crucial role by quickly handling the interrupt and
allowing normal execution to continue smoothly.
When multiple I/O devices like a keyboard, printer, and disk controller send interrupt requests
at the same time, the operating system uses an interrupt handling mechanism to manage them
properly.
First, all interrupt signals go to an interrupt controller. The interrupt controller checks which
devices are requesting service and decides their priority. Each device is given a priority level.
For example, the disk may have higher priority than the printer because disk operations are
more important.
The CPU finishes its current instruction and then accepts the highest-priority interrupt. It saves
the current process information (like registers and program counter) and switches to kernel
mode. Then it looks at the interrupt vector table to find the correct Interrupt Service
Routine (ISR) for that device.
The ISR is a small program that handles the device’s request. It may read data, write data, or
clear the interrupt signal. After finishing one interrupt, the CPU checks if other interrupts are
waiting and handles them one by one according to priority.
Once all interrupts are handled, the CPU restores the previous process and continues execution.
In this way, the operating system ensures that all simultaneous interrupts are handled correctly,
with important devices getting attention first.

Even though interrupt-driven I/O is better than polling, it still has some disadvantages.
One disadvantage is interrupt overhead. Every time a device generates an interrupt, the CPU
must stop its current execution, save the context (registers, program counter), switch to kernel
mode, execute the Interrupt Service Routine (ISR), and then restore the previous context. This
context switching takes time and reduces CPU efficiency.
Another disadvantage occurs when there are too many interrupts, especially for high-speed
devices that transfer small amounts of data frequently. This situation is called an interrupt
storm. The CPU may spend most of its time handling interrupts instead of executing useful
processes.
Interrupt-driven I/O is also less efficient for large data transfers. If each small portion of data
generates an interrupt, the overhead becomes high. That is why systems use DMA (Direct
Memory Access) for large block transfers, since DMA reduces the number of interrupts to
usually one per block.

Direct Memory Access (DMA)


Direct Memory Access (DMA) is a technique used in operating systems to transfer large
blocks of data directly between an I/O device and main memory without continuous
involvement of the CPU. It is designed to improve system performance by reducing CPU
overhead during data transfer.

In a system using DMA, a special hardware component called the DMA controller manages
the data transfer. When a process requests an I/O operation (for example, a disk read), the CPU
does not transfer the data itself. Instead, the CPU programs the DMA controller by specifying
the memory address, the number of bytes to transfer, and the direction of transfer (read or
write). After setting up these parameters, the CPU continues executing other processes.
The DMA controller then takes control of the system bus and transfers data directly between
the I/O device and main memory. During this time, the CPU is free to perform other tasks.
Once the entire data block has been transferred, the DMA controller sends an interrupt to the
CPU to indicate completion. The operating system then marks the waiting process as ready to
continue.
DMA improves system performance because:
 t reduces CPU involvement in data transfer.
 It minimizes interrupt overhead (usually one interrupt per block).
 It allows overlapping of computation and I/O operations.
However, DMA may temporarily take control of the memory bus, which can slightly delay
CPU memory access. Despite this, DMA is much more efficient than programmed I/O or
interrupt-driven I/O for large data transfers.
The most common DMA modes are burst mode, cycle stealing mode, and transparent (or
hidden) mode.
In burst mode, the DMA controller takes complete control of the system bus and transfers an
entire block of data continuously. During this time, the CPU is temporarily suspended from
accessing memory because the DMA controller owns the bus. This method allows very fast
data transfer since the whole block is moved in one continuous operation. However, the
disadvantage is that the CPU must wait until the DMA transfer is finished before accessing
memory again, which may slightly delay CPU execution.
In cycle stealing mode, the DMA controller transfers data one word (or a few bytes) at a time
by temporarily taking control of the system bus for a single memory cycle. After each transfer,
the CPU regains control of the bus. In this way, the DMA “steals” small cycles from the CPU.
This reduces CPU waiting time compared to burst mode, but the overall data transfer may take
slightly longer because it is not continuous.
In transparent mode (also called hidden mode), the DMA controller transfers data only when
the CPU is not using the system bus. It monitors CPU activity and uses the bus during idle
cycles. In this mode, the CPU is not interrupted at all, but the data transfer speed may be slower
because the DMA must wait for free bus cycles.
Each mode represents a trade-off between CPU usage and transfer speed. Burst mode gives the
fastest transfer but pauses the CPU. Cycle stealing balances CPU and DMA activity.
Transparent mode avoids CPU interruption but may reduce transfer speed. Modern systems
choose the appropriate mode depending on performance requirements and workload
conditions.
Burst Mode:
CPU blocked ██████████████████████████
DMA transfer ■■■■■■■■■■■■■■■■■■■■■

Cycle Stealing:
CPU exec ■■■■ ■■■■ ■■■■ ■■■■ ■■■■
DMA steal ■ ■ ■ ■

Transparent Mode:
CPU exec ██████████████████████████
DMA uses idle cycles ▒▒▒

Device Interaction Methods in Operating Systems


Device interaction methods describe how the CPU and operating system communicate with
I/O devices to perform input and output operations. Since I/O devices are much slower than
the CPU, efficient interaction methods are essential for good system performance.
There are three main device interaction methods:

1. Programmed I/O (Polling)


In Programmed I/O, the CPU directly controls the data transfer. The CPU sends a command to
the device and then repeatedly checks the device’s status register to see whether it is ready.
This repeated checking is called polling or busy waiting. Once the device becomes ready, the
CPU transfers the data by reading from or writing to the device’s data register.
In this method, the CPU handles every data transfer and cannot perform other useful tasks
while waiting Therefore, Programmed I/O is simple but inefficient.
2. Interrupt-Driven I/O
In interrupt-driven I/O, the CPU issues a command to the device and then continues executing
other processes instead of waiting. When the device completes its operation, it sends an
interrupt signal to the CPU.
The CPU temporarily stops its current execution, saves its context, and executes an Interrupt
Service Routine (ISR) to handle the device. After servicing the device, the CPU resumes its
previous task.
This method improves efficiency because the CPU does not waste time polling the device.

3. Direct Memory Access (DMA)


DMA is used for large data transfers. In this method, the CPU sets up the DMA controller by
providing the memory address, transfer size, and direction. The DMA controller then transfers
data directly between the device and main memory without continuous CPU involvement.
After the transfer is complete, the DMA controller sends a single interrupt to inform the CPU.
DMA greatly improves performance because it reduces CPU overhead and minimizes interrupt
frequency

Device Driver
A device driver is a special program within the operating system that acts as an interface
between the hardware device and the operating system kernel. It allows the OS and application
programs to communicate with hardware devices such as disks, keyboards, printers, network
cards, and display adapters without needing to know the internal details of the hardware.
In simple terms, a device driver translates high-level OS commands (like read or write) into
low-level hardware-specific instructions that the device controller understands.
How a Device Driver Works
When a process requests an I/O operation (for example, reading from a disk):
1. The process makes a system call (e.g., read()).
2. The operating system forwards this request to the appropriate device driver.
3. The device driver writes commands into the device’s control registers.
4. The device performs the operation.
5. When the device finishes, it generates an interrupt.
6. The driver’s Interrupt Service Routine (ISR) handles the interrupt and completes the
operation.
7. The OS then wakes up the waiting process.
Thus, the driver manages communication between hardware and software.
Functions of a Device Driver
A device driver typically:
 Initializes and configures the device
 Sends commands to the device controller
 Handles interrupts from the device
 Transfers data between device and memory
 Manages errors
 Provides a standard interface to the OS

Why Device Drivers Are Important


 They provide abstraction, hiding hardware details.
 They ensure device independence, so programs do not need to change when hardware
changes.
 They improve system stability by controlling hardware access through the kernel.

Types of Device Drivers


1. Character device drivers – Handle devices that transfer data one byte at a time
(keyboard, mouse).
2. Block device drivers – Handle devices that transfer data in blocks (hard disk).
3. Network device drivers – Manage network communication devices

Geometry of HDD
The geometry of a hard disk describes the physical and logical structure used to store and
organize data on the disk. A hard disk drive (HDD) contains one or more rigid circular platters
that are coated with magnetic material. These platters rotate at high speed, allowing data to be
read or written by read/write heads that move across the platter surfaces. Each platter has two
surfaces, and each surface is used to store data.
The surface of every platter is divided into many concentric circles called tracks. Tracks are
the circular paths where data is magnetically recorded. To organize the data further, each track
is divided into smaller parts known as sectors. A sector is the smallest physical storage unit on
the disk and usually stores 512 bytes or 4096 bytes of data. By dividing tracks into sectors,
the disk can store and retrieve data more efficiently.
• The two surfaces of a platter are covered with a magnetic material(copper alloys)
• We store information by recording it magnetically on the platters, and we read
information by detecting the magnetic pattern on the platters.
• A read–write head “flies” just above each surface of every platter.

In a hard disk with multiple platters, tracks that lie directly above and below each other on
different platter surfaces form a structure called a cylinder. When the read/write heads move
to a particular position, they can access all the tracks that form that cylinder without moving
the arm further. This improves the speed of data access.
The read/write head is an important component of a hard disk drive (HDD) that is responsible
for reading data from the disk and writing data onto it. Each platter surface in a hard disk has
its own read/write head. These heads are attached to an actuator arm that moves across the
surface of the spinning platters to access different tracks where data is stored.
The read/write head works very close to the surface of the platter without actually touching it.
A thin layer of air created by the spinning disk keeps the head floating slightly above the
surface. This prevents damage to the disk while allowing the head to accurately read and write
data.
When writing data, the write head creates a magnetic field that changes the magnetic
orientation of tiny areas on the platter surface. These magnetic changes represent binary data
(0s and 1s). When reading data, the read head senses the magnetic patterns stored on the platter
and converts them back into electrical signals that the computer can process.
The read/write heads move quickly from one track to another to locate the required data. This
movement is controlled by the actuator mechanism inside the hard disk. Because the heads are
very sensitive and operate extremely close to the platter surface, any physical shock or dust can
damage them, which may lead to data loss.
In a hard disk drive (HDD), several important time factors affect how quickly data can be
accessed. These include seek time, rotational latency, and transfer time, which together
determine the overall disk performance.
Seek time is the time required for the read/write head to move from its current position to the
specific track where the data is stored. Since the head must physically move across the surface
of the spinning disk, this process takes a small amount of time, usually measured in
milliseconds. Seek time is one of the major factors affecting disk access speed.
Rotational latency (also called rotational delay) is the time the disk must wait for the required
sector to rotate under the read/write head after the head reaches the correct track. Because the
platters spin continuously, the system may need to wait for the correct position of the sector.
The faster the disk rotates (for example 5400 RPM or 7200 RPM), the smaller the rotational
latency.
Transfer time is the time taken to actually read or write the data once the correct sector is
positioned under the read/write head. This depends on the speed at which data can be
transferred from the disk to the computer’s memory.
Another related concept is access time, which is the total time required to retrieve data from
the disk. It is calculated as:
Access Time = Seek Time + Rotational Latency + Transfer Time
These factors together determine how efficiently a hard disk can read and write data. Lower
seek time and rotational latency result in faster disk performance.
• Although the disk platters are coated with a thin protective layer, the head will
sometimes damage the magnetic surface. This accident is called a head crash.
• A head crash normally cannot be repaired; the entire disk must be replaced, and the
data on the disk are lost unless they were backed up to other storage or RAID protected.

Questions
1.A hard disk rotates at 7200 RPM. Calculate the time taken for one complete rotation of the
disk and determine the average rotational latency experienced when accessing a sector on the
disk. Explain the steps used in the calculation.
Solution
A disk rotates at 7200 RPM.
Step 1: Time for one rotation
Time per rotation
=

t = 60 / RPM
60
𝑡=
7200
𝑡 = 0.00833 seconds

Convert to milliseconds:
0.00833 × 1000 = 8.33 ms

Time for one rotation = 8.33 ms


Step 2: Average rotational latency
Average latency = half of one rotation
8.33
=
2

Average rotational latency = 4.17 ms


2. Consider a hard disk where the average seek time is 9 ms, the disk rotates at 6000 RPM, and
the data transfer time for a block is 0.6 ms. Calculate the average rotational latency of the disk
and determine the total disk access time required to read a block of data.

Solution
Given:
Seek time = 9 ms
Disk speed = 6000 RPM
Transfer time = 0.6 ms
Step 1: Rotational latency
Time per rotation
60
= 0.01 s = 10 ms
6000

Average rotational latency


10
= = 5 ms
2

Step 2: Total access time


Access Time = Seek Time + Rotational Latency + Transfer Time
= 9 + 5 + 0.6

Total access time = 14.6 ms

3. A hard disk system contains 5 platters, each with 2 recording surfaces. Each surface has 1500
tracks, and each track contains 400 sectors. If each sector stores 512 bytes, calculate the total
storage capacity of the hard disk in megabytes.
Given:
Platters = 5
Surfaces per platter = 2
Total surfaces
5 × 2 = 10

Tracks per surface = 1500


Total tracks
10 × 1500 = 15000

Sectors per track = 400


Total sectors
15000 × 400 = 6,000,000

Bytes per sector = 512


Total storage
6,000,000 × 512
= 3,072,000,000 bytes

Convert to MB
3,072,000,000
1024

≈ 2930 MB ≈ 2.93 GB

4. Suppose a disk rotates at 5400 RPM and the seek time required to move the read/write head
to the desired track is 8 ms. If the transfer time for the required data block is 0.5 ms, determine
the total time needed to access and read the data block from the disk.
Solution
Given:
Seek time = 8 ms
Disk speed = 5400 RPM
Transfer time = 0.5 ms
Step 1: Time per rotation
60
= 0.0111 s
5400
= 11.11 ms

Step 2: Average rotational latency


11.11
=
2
= 5.55 ms

Step 3: Total access time


= 8 + 5.55 + 0.5

Total access time = 14.05 ms


5. A disk has an average seek time of 7 ms and rotates at 7200 RPM. If a request arrives just
after the desired sector has passed under the read/write head, calculate the maximum rotational
delay and the total worst-case disk access time, assuming a transfer time of 0.4 ms.

Solution
Given:
Seek time = 7 ms
Disk speed = 7200 RPM
Transfer time = 0.4 ms
Step 1: Time for one rotation
60
= 0.00833𝑠
7200
= 8.33 ms

Step 2: Worst-case rotational delay


Worst case = full rotation
= 8.33 ms
Step 3: Worst-case access time
= 7 + 8.33 + 0.4

Worst-case access time = 15.73 ms

Files and Directories

File is a logical storage unit – logical view of stored information

❖ Provides abstraction of the physical storage

❖ File – named collection of related information that is recorded on secondary storage.

❖ Smallest allotment of secondary storage.

❖ Contiguous logical address space

File Attributes
● Name – only information kept in human-readable form
● Identifier – unique tag (number) identifies file within file system
● Type – needed for systems that support different types
● Location – pointer to file location on device
● Size – current file size
● Protection – controls who can do reading, writing, executing
● Time, date, and user identification – data for protection, security, and usage monitoring
● Information about files are kept in the directory structure, which is maintained on the disk
● Many variations, including extended file attributes such as file

In an operating system, when a process opens a file, the system maintains information about
that file using open-file tables. These tables help the operating system manage file access
efficiently. Generally, there are two types of open-file tables: the per-process open-file table
and the system-wide open-file table.
The per-process open-file table is maintained separately for each process. When a process
opens a file, the operating system creates an entry in this table and assigns a file descriptor,
which is a small integer used by the process to refer to that file. The entry in the per-process
table contains information such as the file descriptor, access mode (read, write, or read-write),
and a pointer to the corresponding entry in the system-wide open-file table. This table allows
each process to keep track of the files it has opened.
In operating systems, when a process opens a file, the OS does not give direct access to the file
structure on disk. Instead, it returns a file descriptor, which is a small integer that acts as a
handle for that open file.
Each process has its own file descriptor table. The file descriptor refers to an entry in the
system-wide open file table, which stores information such as the current file offset and access
mode (read or write).
Thus, a file descriptor is the process’s way of interacting with an opened file.

The system-wide open-file table is shared by the entire operating system and contains
information about all files that are currently open in the system. Each entry in this table stores
details such as the file’s current position (offset), file status flags, and a reference count
indicating how many processes are using that file. It also contains a pointer to the file’s
metadata stored on disk. When multiple processes open the same file, they may share the same
entry in the system-wide open-file table.
The open count is an important field maintained by the operating system in the system-wide
open-file table to keep track of how many processes are currently using a particular open file.
When a process opens a file, the operating system creates or references an entry for that file in
the system-wide open-file table and initializes or increments the open count.
If another process opens the same file, the operating system may use the existing entry in the
system-wide table instead of creating a new one. In such a case, the open count is increased
by one to indicate that another process is using the file. This count helps the operating system
monitor how many active references exist for that file.
When a process closes the file, the operating system decreases the open count by one. If the
open count becomes zero, it means that no process is currently using the file. At this point, the
operating system can safely remove the file’s entry from the system-wide open-file table and
release any associated resources.

🔹 File Interface
The operating system provides a simple and consistent file interface. This interface includes
system calls such as:
 open()
 ead()
 write()
 close()
 lseek()
 unlink()
 These system calls allow programs to create, access, modify, and delete files without
knowing how the file system is implemented internally. The OS hides low-level details
and provides abstraction.
 Creating Files We’ll start with the most basic of operations: creating a file. This can be
accomplished with the open system call; by calling open() and passing it the O CREAT
flag, a program can create a new file.
 Here is some example code to create a file called “foo” in the current working directory.
int fd = open("foo", O_CREAT | O_WRONLY | O_TRUNC)
In this example, the program creates the file (O CREAT), can only write to that file
while opened in this manner (O WRONLY), and, if the file already exists, f irst truncate
it to a size of zero bytes thus removing any existing content (O TRUNC).
A file descriptor is just an integer, private per process, and is used in UNIX systems to access
files; thus, once a file is opened, you use the file descriptor to read or write the file, assuming
you have permission to do so.
The file system interface is the abstraction provided by the operating system that allows user
programs to interact with persistent storage in a simple and uniform way. Instead of exposing
the complexity of disks, blocks, and inodes directly to applications, the OS provides a small
set of system calls that hide these low-level details. This abstraction makes files appear as
simple byte arrays that can be opened, read, written, and closed.
At the core of the file system interface is the idea that “everything is a file.” Programs do not
need to know whether the data comes from a regular file, a device, or a pipe. They use the same
interface for all of them. This uniformity greatly simplifies system design and programming.

The open() System Call


The interaction with a file usually begins with the open() system call. When a process calls
open(), it provides a file name and access mode (read, write, or both). If the file exists and
permissions allow access, the OS returns a file descriptor, which is a small integer that acts as
a handle for the open file.
Internally, the OS:
 Searches the directory structure to find the file.
 Checks access permissions.
 Creates an entry in the system-wide open file table.
 Creates an entry in the per-process file descriptor table.
The file descriptor is then used in future operations.
The read() and write() System Calls
Once a file is open, a process can read from or write to it using read() and write().
The read() system call:
 Takes a file descriptor and a buffer.
 Copies data from the file into memory.
 Advances the file offset.
The write() system call:
 Takes a file descriptor and a buffer.
 Copies data from memory into the file.
 Also advances the file offset.
These calls operate on the abstraction of a file as a linear sequence of bytes. The OS handles
the mapping from file offsets to disk blocks behind the scenes.

The close() System Call


When a process finishes using a file, it calls close(). This removes the file descriptor from the
process’s table and decreases the reference count in the system-wide open file table. If no other
process is using the file, the OS releases associated resources.
Closing files is important to:
 Free system resources.
 Ensure data is properly flushed to disk.

The lseek() System Call


The lseek() system call allows a process to change the file offset. This enables random access
to files. By repositioning the offset, a process can read or write at any location within the file.
This flexibility is essential for applications like databases and large data processing systems.

The unlink() System Call


The unlink() call removes a file name from the directory. However, the actual file data is not
immediately deleted. The file remains on disk until:
 The link count becomes zero.
 No process has the file open.
This design allows safe file deletion even if a process is still using the file.
🔹 Sequential and Random Access
 Files support two main access methods:
Sequential Access
 In sequential access, the file is accessed in order. Each read or write operation moves
the file offset forward automatically. This model is simple and natural for many
applications such as text processing.
 In sequential access, a file is accessed in order, starting from the beginning and
moving forward step by step. Each time a process calls read() or write(), the operating
system automatically advances the file offset to the next position.

 The process does not need to manually specify where to read or write next. This
method is simple and efficient for many applications such as reading text files, log
files, or streaming data. Sequential access matches the natural structure of many tasks,
like reading a book page by page. Because of its simplicity, it is widely used and easy
to implement.

Random Access / Direct Access Method


 In random access, a process can move the file offset to any location using a system call
like lseek(). This allows direct access to any part of the file, which is useful in databases
and structured data storage.
 The file offset plays an important role in both methods.

 Random access (also called direct access) allows a process to move to any location
within a file before performing a read or write operation. This is typically done using
a system call such as lseek(), which changes the file offset to a specified position.
After adjusting the offset, the process can read or write data at that exact location.

 Random access is especially important for applications like databases, file systems,
and large structured data files, where specific records need to be accessed quickly
without reading the entire file. It provides flexibility and efficiency when data is not
processed strictly in order.

 The main difference between sequential and random access lies in how the file offset
is managed. In sequential access, the offset moves automatically and continuously
forward. In random access, the offset can be repositioned to any point in the file. Both
methods are supported by modern operating systems, and the choice between them
depends on the needs of the application. Sequential access is simpler and well-suited
for linear data processing, while random access provides greater flexibility for
complex data retrieval tasks.
Read and Write Files
 The read() system call copies data from the file into a buffer in memory.
The write() system call copies data from memory into the file.
 Internally, the OS:
 Checks permissions
 Uses the file descriptor to locate the file
 Updates the file offset after the operation
 These operations allow controlled and secure data transfer between memory and
storage.

Removing Files
 In systems like UNIX, removing a file does not immediately erase its data. Instead, the
unlink() system call removes the file name from the directory.
 The file’s data remains on disk until:
 No directory entries refer to it
 No process has it open
 This design improves flexibility and supports advanced file management.

Hard Links
 A hard link is another directory entry that points to the same inode (same underlying
file data).
 Key idea:
Multiple names can refer to the same file.
 The file is only deleted when:
 The link count becomes zero
 No process has the file open
 Hard links cannot span different file systems and usually cannot link directories.

Symbolic Links (Soft Links)


 A symbolic link is a special file that contains the path name of another file.
 Unlike a hard link:
 It does not point directly to the inode.
 It acts like a pointer or shortcut.
 If the original file is deleted, the symbolic link becomes invalid (a dangling link).
 Symbolic links are more flexible because they can:
 Cross file systems
 Refer to directories

You might also like