Operating System and Unix Sem2
Operating System and Unix Sem2
int main() {
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];
int burst_time[] = {10, 5, 8};
int quantum = 2; // Time quantum for RR
findavgTime(processes, n, burst_time, quantum);
return 0;
}
4. Algorithm Evaluation
Evaluating scheduling algorithms is done through
simulations and measuring performance metrics like
turnaround time, waiting time, and CPU utilization.
5. Multiple Processor Scheduling
In multiprocessor systems, scheduling can be more
complex. Techniques include:
• Load Balancing: Distributing processes evenly
across processors.
• Affinity Scheduling: Keeping processes on the
same processor to improve cache performance.
6. Real-Time Scheduling
Real-time systems require timely processing to meet
deadlines. Scheduling algorithms used in real-time
systems include:
• Rate Monotonic Scheduling (RMS): Assigns
priorities based on the frequency of process
requests.
• Earliest Deadline First (EDF): Prioritizes processes
with the nearest deadlines.
I/O Devices Organization
1. I/O Devices Organization
I/O devices are organized into a hierarchy based on
their speed, size, and access method. Common types
include:
• Block Devices: Read/write operations in blocks
(e.g., hard drives).
• Character Devices: Read/write operations are
done one character at a time (e.g., keyboard).
2. I/O Buffering
I/O buffering involves using memory space to hold data
temporarily while it is being transferred between the
device and the main memory. This improves
performance by allowing the CPU to continue
processing while waiting for I/O operations to
complete.
Types of buffering include:
• Single Buffering: One buffer used for I/O.
• Double Buffering: Two buffers used to hold data,
allowing overlap of I/O and processing.
• Circular Buffering: A fixed-size buffer treated as a
circular queue.
Example of I/O Buffering in C:
c
Copy code
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
char buffer[100];
sem_t semaphore;
int main() {
pthread_t threads[5];
int ids[5] = {0, 1, 2, 3, 4};
typedef struct {
int page_number;
char data[PAGE_SIZE]; // Page data
} Page;
int main() {
// Simulate paging by allocating pages
int num_pages = 5;
Page* pages = malloc(num_pages * sizeof(Page));
// Accessing pages
for (int i = 0; i < num_pages; i++) {
printf("Page %d: %s\n", pages[i].page_number,
pages[i].data);
}
vi Editor Overview
vi (Visual Editor) is a powerful text editor commonly
used in Unix and Linux systems. It operates in different
modes and offers a variety of commands for text
manipulation.
1. General Startup of vi
To start the vi editor, use the following command in the
terminal:
bash
Copy code
vi filename
• If filename exists, it opens the file for editing. If it
doesn't exist, vi creates a new file with that name.
2. Modes of vi
The vi editor has three primary modes:
• Normal Mode: The default mode for navigation
and command execution.
• Insert Mode: Used for inserting text.
• Command-Line Mode: Used for entering
commands that affect the editor or file.
Switching Between Modes
• To enter Insert Mode, press i (insert before the
cursor), a (append after the cursor), or o (open a
new line).
• To return to Normal Mode, press Esc.
• To enter Command-Line Mode, press : in Normal
Mode.
3. Creating and Editing Files
• To create a new file, use vi newfile.txt.
• After opening the file, switch to Insert Mode to
start typing.
• Save changes and exit with the command :wq in
Command-Line Mode.
4. Features of vi
• Syntax Highlighting: Automatically highlights
syntax based on the file type (in vim).
• Undo/Redo: Press u to undo changes and Ctrl + r
to redo.
• Search and Replace: Easily find and replace text
within the document.
5. Screen Movement
• Move the cursor with arrow keys or:
o h (left)
o j (down)
o k (up)
o l (right)
6. Cursor Movement
• To move by words: w (to the start of the next
word), b (to the start of the previous word).
• To move to the beginning or end of a line: 0
(beginning), $ (end).
• To move to specific line numbers: :n, where n is
the line number.
7. Insertion
• Press i, a, or o to insert text.
• To exit Insert Mode and return to Normal Mode,
press Esc.
8. Deletion
• To delete characters, use x in Normal Mode.
• To delete a whole line, use dd.
• To delete multiple lines, use ndd (where n is the
number of lines).
9. Searching
• To search for a text string, use /string (for forward
search) or ?string (for backward search).
• Press n to repeat the search in the same direction
and N to search in the opposite direction.
10. Submitting Operations
• To save the file, type :w.
• To quit without saving changes, type :q!.
11. Yank, Put, and Delete Commands
• Yank (copy): yy to copy a line.
• Put (paste): p to paste after the cursor or P to
paste before the cursor.
• Delete: Use d followed by movement commands
(e.g., dw to delete a word, dd to delete a line).
12. Reading & Writing Files
• Reading a file: Use :r filename to insert the
contents of another file into the current file.
• Writing a file: Use :w filename to save the current
buffer to a new file.
13. .exrc File for Setting Parameters
The .exrc file allows users to set vi parameters. Create a
.exrc file in your home directory with settings such as:
plaintext
Copy code
set number " Show line numbers
set tabstop=4 " Set tab width to 4 spaces
14. Advanced Editing Techniques
• Macros: Record a sequence of commands using q
followed by a letter to start recording, perform the
commands, then press q again to stop. Execute
with @letter.
• Search and Replace: :%s/old/new/g replaces all
occurrences of "old" with "new".
15. Vim (Improved vi)
Vim (Vi IMproved) is an extended version of vi that
includes many enhancements:
• Syntax Highlighting: Automatic syntax highlighting
for various programming languages.
• Multi-level Undo: Supports multiple undo levels.
• Split Windows: Allows editing multiple files in one
window.
• Plugins: Support for plugins to enhance
functionality.
Shell: Meaning and Purpose
A shell is a command-line interface that allows users to
interact with the operating system. It acts as an
intermediary between the user and the kernel,
interpreting commands and executing them. The
primary purposes of the shell include:
• Command Execution: Users can run programs and
scripts.
• File Management: Users can manipulate files and
directories.
• Automation: Users can write scripts to automate
tasks.
Types of Shell
Several types of shells are available in Unix/Linux
systems, each with unique features:
1. Bourne Shell (sh): The original Unix shell, known
for its simplicity.
2. Bourne Again Shell (bash): An enhanced version of
sh with additional features like command history
and improved scripting capabilities.
3. C Shell (csh): Similar to the C programming
language, offering features like job control and
aliases.
4. Korn Shell (ksh): Combines features of sh and csh,
with enhancements for scripting.
5. Z Shell (zsh): An extended version of bash with
powerful features like spell checking and globbing.
The Command Line
The command line is where users enter commands to
interact with the shell. A typical command format is:
bash
Copy code
command [options] [arguments]
• Command: The name of the program to execute.
• Options: Flags to modify the command's behavior
(usually preceded by -).
• Arguments: Additional inputs for the command,
such as file names.
Standard Input and Standard Output
• Standard Input (stdin): The default source of input
for commands, usually the keyboard.
• Standard Output (stdout): The default destination
for output from commands, usually the terminal.
Redirection
Redirection allows users to change the standard input
and output. Common redirection operators include:
• >: Redirect stdout to a file (overwrite).
bash
Copy code
command > output.txt
• >>: Redirect stdout to a file (append).
bash
Copy code
command >> output.txt
• <: Redirect stdin from a file.
bash
Copy code
command < input.txt
Pipes
Pipes allow users to connect the output of one
command to the input of another using the | operator.
bash
Copy code
command1 | command2
This command executes command1, and its output is
used as input for command2.
Filters
Filters are commands that process input and produce
output. Common filter commands include:
• grep: Search for patterns in text.
• sort: Sort lines of text.
• uniq: Remove duplicate lines.
Special Characters for Searching Files and Pathnames
• Wildcard Characters:
o *: Matches zero or more characters (e.g., *.txt
matches all .txt files).
o ?: Matches a single character (e.g., file?.txt
matches file1.txt, fileA.txt, etc.).
o [...]: Matches any one character within the
brackets (e.g., file[1-3].txt matches file1.txt,
file2.txt, file3.txt).
Built-ins
Built-in commands are part of the shell and do not
require an external program to execute. Examples
include:
• cd: Change the current directory.
• echo: Display a line of text.
• exit: Exit the shell.
Functions
Functions are reusable blocks of code defined by the
user in a shell script, allowing for modular
programming.
bash
Copy code
function_name() {
# commands
}
History
The shell maintains a history of commands executed by
the user, allowing for easy recall and reuse.
• To view history: history
• To execute the last command: !!
• To execute a specific command from history: !n
(where n is the command number).
Aliases
Aliases are shortcuts for commands, allowing users to
create simpler or customized commands.
bash
Copy code
alias ll='ls -l'
Job Control
Job control allows users to manage multiple processes
in the shell. Key commands include:
• &: Run a command in the background.
• jobs: List background jobs.
• fg: Bring a background job to the foreground.
• bg: Resume a suspended job in the background.
File Substitution
File substitution refers to the use of special characters
to represent files or directories in commands, such as *
for wildcard matching.
Source Code Management - RCS and CVS
• RCS (Revision Control System): A version control
system that keeps track of changes to files,
allowing users to retrieve previous versions.
• CVS (Concurrent Versions System): An extension
of RCS that supports multiple developers working
on the same project simultaneously.
awk Utility
awk is a powerful text-processing tool used for pattern
scanning and processing. It is particularly useful for
extracting and manipulating data from files or input
streams. The basic syntax is:
bash
Copy code
awk 'pattern { action }' filename
Example: Print the first column of a file:
bash
Copy code
awk '{ print $1 }' file.txt
Features of Linux
1. Open Source: Linux is free to use, modify, and
distribute, which encourages collaboration and
innovation.
2. Multiuser Capability: Multiple users can access the
system simultaneously without interfering with
each other.
3. Multitasking: Linux can run multiple tasks at the
same time, enhancing efficiency.
4. Portability: Linux can run on various hardware
platforms, from servers to embedded systems.
5. Security: Linux is known for its strong security
features, including user permissions and robust
firewall configurations.
6. Stability and Reliability: Linux systems are less
prone to crashes and can run for long periods
without requiring a reboot.
7. Flexibility: Users can customize and configure the
system to meet their specific needs, including the
desktop environment and applications.
8. Support for Networking: Linux includes extensive
networking capabilities and protocols, making it
ideal for servers and networking applications.
9. Large Community Support: A vast community of
developers and users contributes to ongoing
improvements, support, and documentation.
Drawbacks of Linux
1. Learning Curve: New users may find Linux
challenging to learn, especially those used to
graphical interfaces.
2. Compatibility Issues: Some proprietary software
applications may not be available or fully
compatible with Linux.
3. Hardware Compatibility: While Linux supports
many devices, some hardware may not have
available drivers, leading to functionality issues.
4. Limited Gaming Support: While improving, the
availability of games on Linux is still less than on
other operating systems.
5. Fragmentation: The existence of numerous
distributions can lead to confusion and
inconsistencies in applications and system
management.
Components of Linux
1. Kernel: The core component that manages system
resources and hardware communication.
2. System Libraries: Standard libraries that provide
basic functions for applications, enabling them to
interact with the kernel.
3. System Utilities: Essential tools and applications
for system management and configuration.
4. Shell: A command-line interface that allows users
to interact with the kernel and execute commands.
5. User Interface: Graphical user interfaces (GUIs)
such as GNOME, KDE, or Xfce for user interaction.
Memory Management Subsystems
• Virtual Memory: Linux uses virtual memory to
manage memory efficiently, allowing applications
to use more memory than physically available.
• Paging: Memory is divided into pages, which can
be swapped between physical memory and disk
storage.
• Memory Allocation: The kernel manages memory
allocation and deallocation for processes through
system calls like malloc and free.
• Caching: Frequently accessed data is cached in
RAM to speed up access and improve
performance.
Linux Process and Thread Management
• Process Management: The kernel manages
processes using process control blocks (PCBs) that
store process information such as state, priority,
and memory usage.
• Thread Management: Linux supports
multithreading, allowing multiple threads within a
process to run concurrently.
• Scheduling: The Linux kernel uses scheduling
algorithms (like Completely Fair Scheduler - CFS) to
allocate CPU time to processes and threads.
• Inter-process Communication (IPC): Various IPC
mechanisms, such as pipes, message queues, and
shared memory, allow processes to communicate
with each other.
File Management System
• File System Structure: Linux uses a hierarchical file
system structure with directories and files
organized in a tree-like format.
• File Types: Supports various file types, including
regular files, directories, symbolic links, and special
files.
• File Permissions: Users and groups can have
different permissions (read, write, execute) for
files, ensuring security.
• Mounting File Systems: File systems can be
mounted dynamically, allowing users to access files
on different storage devices.
• File System Types: Supports multiple file systems,
including ext4, XFS, Btrfs, and FAT32.
Device Drivers
• Kernel Modules: Device drivers are often
implemented as kernel modules that can be
loaded or unloaded as needed.
• Hardware Abstraction: Device drivers provide a
layer of abstraction between the hardware and the
kernel, allowing the kernel to interact with
hardware devices without needing specific
knowledge of them.
• Support for Various Devices: Linux supports a
wide range of devices, including storage, network,
and peripheral devices, through drivers.
Entering the Machine
To access a Linux system, you typically use a terminal or
console. If you're using a remote server, you might use
an SSH (Secure Shell) client to log in:
bash
Copy code
ssh username@hostname
User Names and Groups
• Usernames: Each user has a unique username that
identifies them on the system.
• Groups: Users can belong to one or more groups,
which manage permissions for file access and
execution. You can check your groups with:
bash
Copy code
groups
Logging In
When logging in, you'll enter your username and
password. Upon successful login, you'll have access to
the system.
Correcting Typing Mistakes
While typing commands, you can:
• Use the Backspace key to delete characters.
• Use the Arrow keys to navigate through the
command history.
• Press Ctrl + U to delete the entire line.
• Press Ctrl + W to delete the last word.
Format of Linux Commands
A basic Linux command structure is:
bash
Copy code
command [options] [arguments]
• command: The command to execute.
• options: Flags that modify the command behavior
(e.g., -l, -a).
• arguments: The target of the command (e.g.,
filenames or directories).
Changing Your Password
To change your user password, use the passwd
command:
bash
Copy code
passwd
Follow the prompts to enter your current password and
set a new one.
Characters with Special Meanings
Certain characters have special meanings in Linux:
• ~: Represents the home directory of the current
user.
• /: Represents the root directory.
• .: Represents the current directory.
• ..: Represents the parent directory.
• *: Wildcard that matches any number of
characters.
• ?: Wildcard that matches a single character.
• &: Run a command in the background.
• |: Pipe output from one command to another.
Linux Documentation
You can access documentation using the man (manual)
command:
bash
Copy code
man command_name
Example: To read the manual for the ls command:
bash
Copy code
man ls
You can also use info for more detailed documentation.
The File System
Linux uses a hierarchical file system where everything is
organized in a tree structure, starting from the root
directory /.
Current Directory
To check the current working directory, use the pwd
(print working directory) command:
bash
Copy code
pwd
Looking at the Directory Contents
To list the contents of a directory, use the ls command:
bash
Copy code
ls # List files in the current directory
ls -l # Long format (detailed view)
ls -a # Show hidden files (those starting with .)
Absolute and Relative Pathnames
• Absolute Pathname: The full path to a file or
directory, starting from the root directory. For
example:
bash
Copy code
/home/username/Documents/file.txt
• Relative Pathname: A path relative to the current
directory. For example, if you are in
/home/username:
bash
Copy code
Documents/file.txt
Some Linux Directories and Files
Here are some important directories in a typical Linux
file system:
• /: Root directory.
• /home: Contains user home directories.
• /etc: Configuration files for the system.
• /var: Variable data files (e.g., logs).
• /usr: User applications and files.
• /bin: Essential command binaries.
• /sbin: System binaries for administrative tasks.