0% found this document useful (0 votes)
31 views102 pages

IV Sem - Aiml - Os Lab Manual-2024-25

The document is a laboratory manual for the Principles of Operating Systems Lab (22 AMC 09) at Chaitanya Bharathi Institute of Technology, detailing the course structure, objectives, outcomes, and experiments. It outlines the vision and mission of the institute and department, along with program educational objectives, outcomes, and specific outcomes related to artificial intelligence and machine learning. The manual includes a comprehensive list of experiments, assessment procedures, and references for further reading.

Uploaded by

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

IV Sem - Aiml - Os Lab Manual-2024-25

The document is a laboratory manual for the Principles of Operating Systems Lab (22 AMC 09) at Chaitanya Bharathi Institute of Technology, detailing the course structure, objectives, outcomes, and experiments. It outlines the vision and mission of the institute and department, along with program educational objectives, outcomes, and specific outcomes related to artificial intelligence and machine learning. The manual includes a comprehensive list of experiments, assessment procedures, and references for further reading.

Uploaded by

kalvapushpa97
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 102

Laboratory Manual

DEPARTMENT OF ARTIFICAL INTELLIGENCE AND

PROGRAM - B.E
PRINCIPLES OF OPERATING SYSTEMS (22 AMC 09)
( CSE-AI&ML)
SEMESTER - IV

R-22 Regulation

MACHINE LEARNING (AI & ML)

Prepared by: …Dr.Garlapati Narayana Verified by: ……………

CHAITANYA BHARATHI INSTITUTE OF TECHNOLOGY


(An Autonomous Institution, Affiliated to Osmania University, Approved by AICTE,
Accredited by NAAC with A++ Grade and Programs Accredited by NBA)
Chaitanya Bharathi Post, Gandipet, Kokapet (Vill.), Hyderabad, Ranga Reddy - 500 075, Telangana
www.cbit.ac.in

1|Page
CHAITANYA BHARATHI INSTITUTE OF TECHNOLOGY
(An Autonomous Institution, Affiliated to Osmania University, Approved by AICTE,
Accredited by NAAC with A++ Grade and Programs Accredited by NBA)
Chaitanya Bharathi Post, Gandipet, Kokapet (Vill.), Hyderabad, Ranga Reddy - 500 075, Telangana
www.cbit.ac.in
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE
LEARNING (AI&ML)

Name of the Lab Course:


PRINCIPLES OF OPERATING SYSTEMS LAB
(22AMC09)
INDEX
Item Page

No

Institute Vision, Institute Mission, Quality Policy, Department Vision


2
and Department Mission

Program Educational Objectives (PEOs), Program Outcomes (POs)


3
and Program Specific Outcomes (PSOs)

Syllabus 7

Course Introduction 8

Assessment Procedure of CIE and SEE 9-10

General Instructions for Laboratory Classes 11

Concluding Remarks / Gap Analysis 16

2|Page
LABORATORY / PRACTICAL
Exp Pag
Laboratory / Practical CO BTL
No e No
1 Shell programming.
1 2,3 28
2 Demonstration and Performance Evaluation of CPU scheduling
algorithms
3 Implementation of memory management techniques like 4 2,3,4 71
paging and segmentation.
4 Implementation of Linked, Indexed and Contiguous file 4 2,3,4 77
allocation methods.
5 Demonstration of Linux/Unix file related system calls: mkdir, 1,2 2,3 14
link, unlink, mount, unmount, users+, chown, chmod, open,
close, read, write, lseek, stat, sync.
6 Implementation of producer-consumer, readers- writers and dining philosophers
problem using semaphores
7 Demonstration of Bankers Algorithm for Deadlock Avoidance. 5 2,3,4 37

8 Development of applications using Linux/Unix system calls: 6 6 89


signal, socket, accept, snd, recv, connect.
Experiments Beyond curriculum (Open ended / Structured enquiry)
1 Demonstrate First Come First Serve CPU scheduling 4,5 3,4 47

2 Demonstrate non preemptive Shortest Job First or Shortest Job 4,5 3,4 48
next CPU scheduling.
3 Demonstrate pre-emptive Shortest Job First or Shortest Job 4,5 3,4 49
next CPU scheduling
4 Demonstrate Round Robin CPU scheduling 4,5 3,4 52

5 Demonstrate Non Pre-emptive Priority CPU Scheduling 4,5 3,4 54

6 Demonstrate Preemptive Priority CPU Scheduling 4,5 3,4 55

7 Demonstrate the use of atexit() , _exit() handler 2 3,4 60

8 Demonstrate the use of wait() , waitpid() and waitid() 2 3,4 62

9 Demonstrate the use of wait3() and wait4() 2 3,4 65

10 Demonstrate the use of set setresuid(), setresgid(), setfsuid() and 2 3,4 69


setfsgid()
11 Demonstrate Banker’s algorithm (Resource Allocation) 4,5 3,4 78

12 Demonstrate the use of shared memory – IPC 6 3,4 88

3|Page
Note:
a) Minimum 12 experiments should be included in every course other than
experiments beyond syllabus.
b) Add project/ case studies/ student defined experiments for the courses having
experiments less than 12 in syllabus.
c) Include Minimum 2 experiments beyond prescribed experiments meeting industry
problems to challenge student learning.

4|Page
CHAITANYA BHARATHI INSTITUTE OF TECHNOLOGY
(An Autonomous Institution, Affiliated to Osmania University, Approved by AICTE,
Accredited by NAAC with A++ Grade and Programs Accredited by NBA)
Chaitanya Bharathi Post, Gandipet, Kokapet (Vill.), Hyderabad, Ranga Reddy - 500 075, Telangana
www.cbit.ac.in

Vision of Institute
To be the Centre of Excellence in Technical Education and
Research.

Mission of Institute
To address the Emerging needs through Quality Technical
Education and Advanced Research.

Quality Policy
CBIT imparts value based Technical Education and Training to
meet the requirements of students, Industry, Trade/
Profession, Research and Development Organizations for Self-
sustained growth of Society.

5|Page
CHAITANYA BHARATHI INSTITUTE OF TECHNOLOGY
(An Autonomous Institution, Affiliated to Osmania University, Approved by AICTE,
Accredited by NAAC with A++ Grade and Programs Accredited by NBA)
Chaitanya Bharathi Post, Gandipet, Kokapet (Vill.), Hyderabad, Ranga Reddy - 500 075, Telangana
www.cbit.ac.in
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE
LEARNING (AI&ML)

Vision of the Department


To produce professionals in artificial intelligence and machine learning through the best possible
education, acquire international recognition as a destination, and advance society in exciting and
creative ways.
Mission of the Department
 Impart rigorous training to generate knowledge through the state-of-the-art concepts and
technologies in Artificial Intelligence and Machine Learning.
 Develop technical proficiency in students through creativity and leadership.
 Encourage lifelong learning, social responsibility, environmental conservation, and professional
ethics.
 Establish centres of excellence in leading areas of computer and artificial intelligence
disciplines.

Program Educational Objectives (PEOs)

PEO1: Using a solid foundation in mathematical, scientific, engineering, and current computing
Principles, formulate, analyse, and resolve engineering issues.
PEO2: Apply artificial intelligence theory and concepts to analyse the requirements, realise technical
Specifications, and design engineering solutions.
PEO3: Through cross-disciplinary projects and a variety of professional activities, demonstrate
technical proficiency, AI competency, and foster collaborative learning and a sense of teamwork.
PEO4: Provide graduates with solid knowledge, competence, and soft skills that will enable them to
ethically contribute to societal demands and achieve sustainable advancement in emerging
computer technologies through lifelong learning.

6|Page
CHAITANYA BHARATHI INSTITUTE OF TECHNOLOGY
(An Autonomous Institution, Affiliated to Osmania University, Approved by AICTE,
Accredited by NAAC with A++ Grade and Programs Accredited by NBA)
Chaitanya Bharathi Post, Gandipet, Kokapet (Vill.), Hyderabad, Ranga Reddy - 500 075, Telangana
www.cbit.ac.in
DEPARTMENT OF ARTIFICIAL INTELLIGENCE
AND MACHINE LEARNING (AI&ML)

Program Outcomes (POs)


Engineering Knowledge: Apply the knowledge of mathematics, science,
engineering fundamentals and an engineering specialization for the solution
of complex engineering problems

Problem analysis: Identify, formulate, research literature, and analyse


complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.

Design/development of solutions: Design solutions for complex


engineering problems and design system components or processes that meet
the specified needs with appropriate consideration for public health and
safety, and cultural, societal, and environmental considerations.

Conduct investigations of complex problems: Use research-based


knowledge and research methods including design of experiments, analysis
and interpretation of data, and synthesis of the information to provide valid
conclusions.

Modern tool usage: Create, select, and apply appropriate techniques,


resources, and modern engineering and IT tools, including prediction and
modelling to complex engineering activities, with an understanding of the
limitations.

The engineer and society: Apply reasoning informed by the contextual


knowledge to assess societal, health, safety, legal, and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.

7|Page
Environment and sustainability: Understand the impact of the
professional engineering solutions in societal and environmental contexts,
and demonstrate the knowledge of, and need for sustainable development.

Ethics: Apply ethical principles and commit to professional ethics and


responsibilities and norms of the engineering practice.

Individual and team work: Function effectively as an individual, and as a


member or leader in diverse teams, and in multidisciplinary settings.

Communication: Communicate effectively on complex engineering activities


with the engineering community and with the society at large, such as, being
able to comprehend and write effective reports and design documentation,
make effective presentations, and give and receive clear instructions.

Project management and finance: Demonstrate knowledge and


understanding of the engineering and management principles and apply
these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.

Life-long learning: Recognise the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest context
of technological change.

Program Specific Outcomes (PSOs)

PSO1. Apply the principal concepts of AI Engineering to design, develop,


deploy and prototype AI Subsystems.

PSO2. Apply the knowledge gained pertaining to data storage, data analytics
and AI concepts to solve real world business problems.

PSO3. Apply, analyse, design, develop, and test principles of AI concepts on


Intelligent Systems.

8|Page
20AMC09
PRINCIPLES OF OPERATING SYSTEMS LAB
Instruction 3 Hours per week
Duration of End Examination 3 Hours
Semester End Examination 50 Marks
Continuous Internal Evaluation 50 Marks
Credits 1

Pre-requisites: Programming for problem solving.

Course Objectives: The objectives of this course are,


1. To explore Unix/Linux operating system.
2. To analyze various system calls available in Linux/Unix.

Course Outcomes: On Successful completion of this course, student will be able to,
1. Understand Linux/Unix environment.
2. Understand and implement shell programming.
3. Simulate memory management and file allocation techniques.
4. Analyze process and file management system calls by creating and/or modifying concurrent programs.
5. Build network-oriented applications using system calls.

List of Experiments:
1. Shell programming.
2. Demonstration and Performance Evaluation of CPU scheduling algorithms
3. Implementation of memory management techniques like paging and segmentation.
4. Implementation of Linked, Indexed and Contiguous file allocation methods.
5. Demonstration of Linux/Unix file related system calls: mkdir, link, unlink, mount, unmount, users+, chown,
chmod, open, close, read, write, lseek, stat, sync.
6. Implementation of producer-consumer, readers- writers and dining philosophers problem using semaphores
7. Demonstration of Bankers Algorithm for Deadlock Avoidance.
8. Development of applications using Linux/Unix system calls: signal, socket, accept, snd, recv, connect.
Text Books:
1. Galvin, Silberschatz, “Operating System Concepts”, 10th Edition, John Wiley & Sons, 2018.
2. Dhananjay Dhamdhare, “Operating Systems-A Concept Based Approach”, 3rd Edition, McGraw Hill Education,
2017.

Suggested Reading:
1. Ekta Walia, “Operating System Concepts”, Khanna Book Publishing, 2020.
2. William Stallings, “Operating Systems Internals and Design Principles”, Pearson Ed., 2012.
3. Charles Crowley, “Operating Systems –A Design Oriented Approach”, McGraw Hill Education, 2017.
1. Andrew S. Tanenbaum, Albert S Woodhull, “Operating systems Design and Implementation”, Pearson Ed., 2009.

Mapping of Course Outcomes with Program Outcomes and Program Specific Outcomes:
PO/PSO PO PO PO PO PO PO PO PO PO PO PO PO PSO PSO PSO
CO 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
CO 1 2 1 1 1 1 1
CO 2 2 2 1 1 1
CO 3 2 2 1 2 1
CO 4 2 2 2 1 1 1 1
CO 5 2 1 1 1 1 1 1

9|Page
COURSE INTRODUCTION
Name of the Lab Course:
PRINCIPLES OF OPERATING SYSTEMS LAB (20AMC09)
An Operating Systems (OS) Lab course is designed to complement theoretical
knowledge gained in an Operating Systems lecture course by providing hands-on
experience with practical aspects of operating system concepts. The lab course
typically involves a series of experiments and projects that allow students to apply
their understanding of operating systems principles to real-world scenarios. Here are
key aspects typically covered in an Operating Systems Lab course: Environmental
Setup, Process management, Memory management, concurrency and synchronization,
File allocation techniques, paging , segmentation, networking and distributed sytems,
security and protection.

Applications of Operating Systems Lab:


1. Process and Memory Management:
Application: Understanding and implementing process creation, scheduling, and
memory management.
Benefits: Students gain practical insights into process synchronization, inter-process
communication, and memory allocation.

2. File System Operations:


Application: Designing, implementing, and analyzing file system operations.
Benefits: Students learn about file organization, directory structures, and file access
methods through hands-on projects.

3. I/O System Interaction:


Application: Experimenting with I/O operations and device drivers.
Benefits: Students gain practical experience in managing I/O devices, handling
interrupts, and optimizing I/O performance.

4. Concurrency and Synchronization:


Application: Developing concurrent programs and implementing synchronization
mechanisms.
Benefits: Students explore solutions to common synchronization problems and
understand the challenges of concurrent programming.

5. Networking Concepts:
10 | P a g e
Application: Implementing simple networking protocols and socket programming.
Benefits: Students gain practical exposure to networked environments, understanding
communication between processes over a network.

6. Security Measures:
Application: Implementing security mechanisms and access control.
Benefits: Students learn about authentication, encryption, and protection mechanisms to
enhance system security.

7. Troubleshooting and Debugging:


Application: Identifying and resolving common OS-related errors and bugs.
Benefits: Students develop skills in troubleshooting, using debugging tools, and
interpreting system logs.

8. Project-Based Learning:
Application: Working on comprehensive OS projects.
Benefits: Students apply integrated knowledge to solve real-world problems, enhancing
problem-solving and project management skills.

9. Performance Analysis:
Application: Analyzing system performance under different scenarios.
Benefits: Students explore tools for performance monitoring and gain insights into
optimizing system efficiency.
ASSESSMENT PROCEDURE AND AWARD OF
CIE MARKS
Following is the subdivision for the internal marks (50) of the Lab:

(i) 20 marks for the lab internal tests

Two tests are to be conducted i.e one test after 1st cycle of experiments
and second test after the second cycle. Average of two tests marks put
together should be consider (20 maximum)

(ii) 30 marks for CIE

For the CIE 30 marks will be awarded based on the rubrics provided below.

This Rubrics are general guideline. Based on the lab type (programming or
hardware) and complexity of the course Rubrics can be customized by the
department in tune to program and course offered. Performance Indicators of the
Rubrics also can be changed by the departments/Program based on the need.

11 | P a g e
RUBRICS

Descriptors and Score

S.
Parameter
No

Outstanding Good Fair Poor Very Poor

1 Pre- Well prepared prepared for Adequately Minimal Lacks


Experiment for the the prepared for preparation preparation
Preparation experimentati experimentati the and without and without
work on with a on with clear experimentatio clear clear
5M clear specifications n without clear specifications specifications
specifications, and specifications and and
plan/design plan/design and plan/design plan/design
and additional (4M) plan/design (2M) (1 M)
information (3M)
(5M)

2 Experimentat Student Student Student solves Student solves Student fails


ion (Problem conducts solves the the problem the problem to solve the
Solving, experiment problem and and conducts with few test problem (2M)
Methodology with all conducts experiment cases with
of possible test experiments with few complexity
Conduction) cases in an with all possible test (4M)
10 M optimized possible test cases with
fashion.(10M) cases (8M) complexity
(6M)

3 Post Demonstrates Demonstrates Demonstrates Demonstrates Failed to


Experiment the results and results and Partial results Demonstrate
Analysis simulation/ inference; inference; and inference; s results and
[Viva, findings Able to Unable to Unable to inference;
Inference] /Hardware answer Few answer the answer the Unable to
5M results Infers Questions Questions Questions answer the
and answer posed by posed by posed by Questions
all the Instructor Instructor. Instructor (2M) posed by
Questions (4M) (3M) Instructor
posed by (1M)
Instructor
(5M)

12 | P a g e
Descriptors and Score

S.
Parameter
No

Outstanding Good Fair Poor Very Poor

4 Report Report meets Report with Report is Report is Report is


Writing all well-organized complete and complete, incomplete,
5M requirements content, adequate with poor grammar unclear, poor
and it is visuals, poor grammar. and grammar and
prepared in graphics, (3M) inadequate inadequate
original and citations and and failed to (1M)
creative way references organize
to engage (4M) thoughts (2M)
readers (5M)

5 Conduct Excellent Follows the Follows safety Followed Does not


(Ethics, team spirit, safety precautions minimum Follows
Safety, Team strictly precautions, and ethical safety safety
Work) 5M follows ethics practices practices and precautions precautions
and safety ethics and failed to and ethical and ethical
precautions poor team exhibit practices and practices and
with good work (4M) teamwork. failed to failed to
team work (3M) exhibit team exhibit team
(5M) work. (2M) work. (1M)

TOTAL SCORE 50

13 | P a g e
ASSESSMENT PROCEDURE AND AWARD OF
SEE MARKS
Paramete Descriptors and Score
r Very
Outstanding Good Fair Poor
Poor
Record The content of all The content of The content The content The
5M the experiments most of the of the most of the few content
is well-organized, experiments of experiments of the all
recorded the are well- experiments is not well- the
tables and neatly organized, are well- organized, experime
drawn graphs. recorded the organized, recorded the nts is not
Results and tables, neatly recorded the tables, neatly well-
discussions are drawn graphs. tables, drawn organize
well presented. Results and neatly drawn graphs. d,
(5M) discussion are graphs. Results and recorded
presented. (4M) Results and discussion are the
discussion not presented tables,
are not (2M) neatly
presented drawn
(3M) graphs.
Results
and
discussio
n are not
presente
d (1M)
Write up Presentation of Presentation of Presentation Presentation Presentat
about the the given the given of the given of the given ion of the
experiment experiment/progr experiment/pro experiment/ experiment/pr given
10M am is very well gram is program is ogram is experime
organized with organized with organized minimal with nt/progra
the required the required and is clear m is
content, content, without clear specifications minimum
specifications, specifications, specification and without
plan/procedure plan/procedure s and plan/design. clear
of the conduct of the conduct. plan/design. (4M) specificat
and all the (8M) (6M) ions and
required plan/desi
additional gn.
information. (2M)
(10M)
Conduction Conducts Conducts Conducts Conducts Failed to
of the experiment / experiment / experiment / experiment / Conducts
experiment Simulate the Simulate the Simulate the Simulate the experime
and problem with problem with problem with problem with nt /
observation proper connections / proper improper Simulate
s connections / all with most of connections / connections / the
15M possible test the test cases. less test less test problem
cases. All the Failed to note cases. cases. (6M) with
possible all observations (9M) improper
observations are (12M) connectio
noted. (15M) ns / less
test
cases.
(3M)
Results & Demonstrates Demonstrates Demonstrate Demonstrates Failed to
Analysis the experimental the s the the partial Demonst
10M results with experimental experimental experimental rate the
adequate results with results, results with results
analysis / required failed to least and
14 | P a g e
Paramete Descriptors and Score
r Very
Outstanding Good Fair Poor
Poor
simulation/ analysis / maximum analysis / least
findings simulation/ analysis / simulation/ analysis /
/obtained findings simulation/ findings. simulatio
results /plotting /obtained findings. (4M) n/
the graphs. results /plotting (6M) findings.
(10M) the graphs. (2M)
(8M)
Viva-Voce Answers most of Answers most Answers only Answers only Failed to
10M the questions of the questions few of the few of the answer
with good with good questions questions questions
analytical explanation. with good with nominal . (2M)
explanation. (8M) explanation. explanation.
(10M) (6M) (4M)
TOTAL SCORE 50

GENERAL INSTRUCTIONS FOR LABORATORY


CLASSES
DO‘S
1. Without Prior permission do not enter into the Laboratory.
2. While entering into the LAB students should wear their ID cards.
3. The Students should come with proper uniform.
4. Students should sign in the LOGIN REGISTER before entering into the
laboratory.
5. Students should come with observation and record note book to the
laboratory.
6. Students should maintain silence inside the laboratory.
7. After completing the laboratory exercise, make sure to shutdown the system
properly
DONT‘S
1. Students bringing the bags inside the laboratory..
2. Students wearing slippers/shoes insides the laboratory.
3. Students using the computers in an improper way.
4. Students scribbling on the desk and mishandling the chairs.
5. Students using mobile phones inside the laboratory.
6. Students making noise inside the laboratory.

Concluding Remarks / Gap Analysis


The Operating Systems Lab is an integral part of a well-rounded computer science curriculum,
providing students with the tools and experiences needed to succeed in the dynamic and ever-evolving
field of operating systems and system development. The hands-on nature of the lab fosters a deep
understanding of system internals and cultivates the skills necessary for success in both academic and
professional pursuits. While the operating systems course encompasses numerous crucial concepts,
15 | P a g e
some are not included in the main curriculum. These particular concepts are addressed through
supplementary experiments beyond the regular course content.

LABORATORY / PRACTICAL INDEX

16 | P a g e
Pag
Exp No Laboratory / Practical CO BTL
e No
WEEK 1 & 2:
Explore the Linux/Unix Commands
i) File/Directory Related
1 1 1 17
ii) Process Related
iii) Network Related
Write a shell script to:
Write a shell script to
i) Check given number is prime or not
ii) Check given number is palindrome number
2 iii) Check given number is Armstrong number 3 2 31
iv) Convert decimal to binary
v) Convert decimal to base 5
vi) Convert base 5 to decimal

WEEK 3:

3 Demostrate System calls with simple example program 2 2 35


Demostrate following I/O system calls with examples:
i) open
ii) read
iii) Write
4 4 3 35
iv)lseek
v)ioctl
vi)stat
vi)syn
Demonstrate following File system call with examples :
i) link
ii) unlink
5 iii) mount 1 2 36
iv)unmount
v) chmod
vi) chown
Demonstrate how process is created and allocate memory
6 4 2 37
in /proc folder with example program.
WEEK 4:
Write a program to demonstrate the use of fork() system call
7 5 2 39

Write a program to demonstrate the use of exe system


calls
8 5 3 40
Parent process --> Execute factorial of given number
Child process --> Execute prime number

Write a program to demonstrate use following exe


functions:
int execl(const char* path, const char* arg, …)
int execlp(const char* file, const char* arg, …)
9 5 3 42
int execle(const char* path, const char* arg, …, char* const
envp[])
int execv(const char* path, const char* argv[])
int execvp(const char* file, const char* argv[])
int execvpe(const char* file, const char* argv[], char
17 | P a g e
*const envp[])
Write a program to demonstrate the use of vfork()
10 5 2 43

Write a program to demonstrate Orphan process


BASIC COMMANDS IN LINUX
WEEK1 & WEEK2

AIM: To study and execute the commands in UNIX

A.
FILE RELATED COMMANDS:

1. Pwd Command:
DESCRIPTION: It displays the present working directory
SYNTAX: pwd
OUTPUT:

2. Cd Command:
DESCRIPTION: It changes the working directory i.e., change the current working to some other folder.
SYNTAX: cd [option] [directory]
OUTPUT:

3. Ls Command:
DESCRIPTION: It lists the content/files listed in a particular UNIX directory
SYNTAX: ls [options] [filename]
OUTPUT:

4. Rm command:
DESCRIPTION: It removes files or directories
SYNTAX: rm [option …] filelist
OUTPUT:
Before using rm command:

After using rm command:

18 | P a g e
5. Mv command:
DESCRIPTION: It is used to move files or directories from one place to another or renames the files.
SYNTAX: mv [option] [sourceFile] [destFile]
If destination file doesn’t exist then it will be created else it will overwrite and the source file is deleted.
OUTPUT:
Renaming the file present in directory

6. Cat Command:
DESCRIPTION: It allows us to create single or multiple files, view content of file, concatenate files and
redirect output in terminal or files.
SYNTAX: cat [option …] [file …]
OUTPUT:
Text file is created

7. Cmp Command:
DESCRIPTION: It compares two files, and if they differ, tells the first byte and line number where they
differ.
SYNTAX: cmp [option …] fromfile tofile
OUTPUT:

19 | P a g e
8. Cp Command:
DESCRIPTION: It copies the files
SYNTAX: cp [option] source destination
OUTPUT:

9. Echo Command:
DESCRIPTION: It is used for displaying a line of string/text that is passed as the arguments
SYNTAX: echo [option] [string]
OUTPUT:

10. Mkdir Command:


DESCRIPTION: It created new directory
SYNTAX: mkdir [options] DirectoryNames
OUTPUT:

11. Paste Command:


DESCRIPTION: It merges the lines from multiple files. It sequentially writes the corresponding lines from
each file separated by a TAB delimiter on the UNIX terminal
SYNTAX: paste [options] files-list
OUTPUT:

20 | P a g e
12. Rmdir Command:
DESCRIPTION: It removes the directories
SYNTAX: rmdir [options] DirectoryNames
OUTPUT:

13. Head Command:


DESCRIPTION: It displays the beginning of a text file or piped data. It prints the first 10 lines of the
specified files.
SYNTAX: head [option] [files]
OUTPUT:

21 | P a g e
14. Tail Command:
DESCRIPTION: It displays the tail end of a text file or piped data. It prints the last 10 line sof the
specified file.
SYNTAX: tail [option] [files]
OUTPUT:

15. Date Command:


DESCRIPTION: It is used to display date, time, time zone, etc. It is also used to set the date and time of
the System. It is used to display the date in different formats and calculate dates over time.
SYNTAX: date [option] [+format]
OUTPUT:

22 | P a g e
16. Grep Command:
DESCRIPTION: It prints lines matching a pattern
SYNTAX: grep [options] PATTERN [file]
OUTPUT:

17. Touch Command:


DESCRIPTION: It creates a new file or update its timestamp
SYNTAX: touch [option …] [File …]
OUTPUT:

18. Chmod Command:


DESCRIPTION: It is used to change the access permissions, change mode
SYNTAX: chmod [options] Mode File
OUTPUT:
Giving access of editing to anyone

23 | P a g e
19. Man Command:
DESCRIPTION: It is the interface to view the system’s reference manuals.
SYNTAX: man ls
OUTPUT:

20. Clear Command:


DESCRIPTION: It clears the terminal Screen
SYNTAX: clear
OUTPUT:
After entering the clear command entire terminal will be cleared

24 | P a g e
PROCESS RELATED COMMANDS:

1. Top Command:
DESCRIPTION: To track the running processes on our machine
SYNTAX: top
OUTPUT:

25 | P a g e
2. Ps Command:
DESCRIPTION: ps is short for Process status. It displays the currently-running processes.
SYNTAX: ps
OUTPUT:

3. Kill Command:
DESCRIPTION: It sends a signal to the process. There are different types of signals that we can send
SYNTAX: kill [number]
OUTPUT:
List of different types of signals

4. Nice Command:
DESCRIPTION: The Nice command configures the priority of a Linux process before it is started. The
renice command sets the priority of an already running process.
SYNTAX: nice -nice_value command-arguments; renice -n nice_value –p pid_of_the_process
OUTPUT:

26 | P a g e
NETWORK RELATED COMMANDS:

1. Ping Command:
DESCRIPTION: It allows us to test the reachability of a device on a network
SYNTAX: ping [host]
OUTPUT:

2. Ifconfig Command:

DESCRIPTION: The command ifconfig stands for interface configurator. This command enables us to
initialize an interface, assign IP address, enable or disable an interface. It displays route and network
interface.
SYNTAX: ifconfig
OUTPUT:

27 | P a g e
3. Netstat Command:
DESCRIPTION: The Netstat command displays active TCP connections, ports on which the computer is
listening. The information this command provides can be useful in pinpointing problems in our network
connections.
SYNTAX: netstat
OUTPUT:

4. Nslookup Command:
DESCRIPTION: NsLookUp command is used to find all the IP addresses for given domain name.
SYNTAX: nslookup host
OUTPUT:

28 | P a g e
5. Telnet Command:
DESCRIPTION: It connects destination via the telnet protocol, if telnet connection establishes on any
port means connectivity between two hosts is working fine.
SYNTAX: telnet hostname/IP address
OUTPUT:

6. Traceroute Command:
DESCRIPTION: A handy utility to view the number of hops and response time to get to a remote system
or website is a traceroute.
SYNTAX: traceroute [OPTION...] HOST
OUTPUT:

CONCLUSION:
By executing the above commands, we have understood the commands.
To Study about UNIX vi Editor and its features:
 The default editor that comes with the UNIX operating system is vi editor (visual editor).
 Using vi editor, we can edit an existing file or create a new file from scratch.
 We can also use this editor to just read a text file
 Syntax: vi filename
29 | P a g e
Modes of Operation in vi editor:
 There are three modes of operation in vi:
- Command Mode:
i. When vi starts up, it is in Command Mode.
ii. This mode is where vi interprets any characters we type as commands and thus does not
display them in the window.
iii. This mode allows us to move through a file, and to delete, copy, or paste a piece of text.
iv. To enter into Command Mode from any other mode, it requires pressing the [Esc] key.
v. If we press [Esc] when we are already in Command Mode, then vi will beep or flash the
screen
- Insert Mode:
i. This mode enables you to insert text into the file.
ii. Everything that’s typed in this mode is interpreted as input and finally, it is put in the file.
iii. The vi always starts in command mode.
iv. To enter text, you must be in insert mode. To come in insert mode you simply type i.
v. To get out of insert mode, press the Esc key, which will put you back into command mode.
- Last Line Mode (Escape Mode):
i. Line Mode is invoked by typing a colon [:], while vi is in Command Mode.
ii. The cursor will jump to the last line of the screen and vi will wait for a command.
iii. This mode enables you to perform tasks such as saving files, executing commands.
Vi Commands:
 To switch from command to insert mode:
- i – Start typing before the current character
- l – Start typing at the start of current line
- a – Start typing after the current character
- A – Start typing at the end of current line
- o – Start typing on a new line after the current line
- O – Start typing on a new line before the current line
 To move around a file:
- j – To move down
- k – To move up
- h – To move left
- l – To move right
 To delete:
- x – Delete the current character
- X – Delete the character before the cursor
- r – Replace the current character
- xp – Switch two characters
- dd – Delete the current line
- D – Delete the current line from current character to the end of the line
- dG – Delete from the current line to the end of the file
 To repeat or undo:
- u – Undo the last command
- . – repeat the last command
 To save and quit:
- :wq – Save and quit
- :w – Save
- :q – Quit
- :w fname – Save as fname
- ZZ – Save and quit
- :q! – Quit discarding changes made
- :w! – Save (and write to non-writable file)
 Command to cut, copy and paste:
- dd – delete a line
30 | P a g e
- yy – (yank yank) copy a line
- p – Paste after the current line
- P – Paste before the current line
- <n>dd – Delete the specified n number of lines
- <n>yy – Copy the specified n number of lines
 Start and end of line:
- 0 – Bring at the start of the current line
- ^ - Bring at the start of the current line
- $ - Bring at the end of the current line
- d0 – Delete till start of a line
- d$ - Delete till end of a line
 Joining lines:
- J – Join two lines
- yyp – Repeat the current line
- ddp – Swap two lines
 Move forward or backward:
- w – Move one word forward
- b – Move one word backward
- <n>w – Move specified number of words forward
- dw – Delete one word
- yw – Copy one word
- <n>dw – Delete specified number of words

31 | P a g e
2.
Aim: Write a shell script to
a. Check given number is prime or not
b. Check given number is palindrome number
c. Check given number is Armstrong number
d. Convert decimal to binary
e. Convert decimal to base 5
f. Convert base 5 to decimal

Program:
a) A Program to check given number is prime or not
PROGRAM:
echo -n "Enter Number : "
read n
for((i=2; i<=$n/2; i++))
do
ans=$(( n%i ))
if [ $ans -eq 0 ]
then
echo "$n is not a prime number."
exit 0
fi
done
echo "$n is a prime number."
OUTPUT:

b) A Program to check given number is palindrome number


Program:
echo "Enter Number: "
read n
num=$n
rev=0
while [ $num -gt 0 ]
do
rev=$((rev*10 + num%10))
num=$((num/10))
done
if [ $rev -eq $n ]
then
echo "$n is a Palindrome"
exit 0
fi
echo "$n is not a Palindrome"

32 | P a g e
OUTPUT:

c) A Program to check given number is Armstrong number


Program:
echo -n "Enter a number: "
read n
t=$n
sum=0
while [ $n -gt 0 ]
do
rem=$((n%10))
cube=$((rem*rem*rem))
sum=$((sum+cube))
n=$((n/10))
done
if [ $sum == $t ]
then
echo "$t is a Armstrong Number"
else
echo "$t is not a Armstrong Number"
fi
OUTPUT:

d) A Program to convert decimal to binary


Program:
echo "Enter any decimal no:"
read num
rem=1
bno=" "
while [ $num -gt 0 ]
do
rem=`expr $num % 2 `
bno=$bno$rem
num=`expr $num / 2 `
done
i=${#bno}
33 | P a g e
final=" "
while [ $i -gt 0 ]
do
rev=`echo $bno | awk '{ printf substr( $0,'$i',1 ) }'`
final=$final$rev
i=$(( $i - 1 ))
done
echo "Equivalent Binary no:" $final

OUTPUT:

e) A Program to convert decimal to base 5


Program:
echo -n "Enter any decimal no: "
read num
rem=1
bno=""
while [ $num -gt 0 ]
do
rem=$((num%5))
bno=$rem$bno
num=$((num/5))
done
echo "The converted base 5 number: $bno"
OUTPUT:

f) A Program to convert base 5 to decimal


Program:
echo -n "Enter Base 5 number: "
read bno
dec=0
pow=1
while [ $bno -gt 0 ]
do
val=$((bno%10))
dec=$((dec+val*pow))
bno=$((bno/10))
pow=$((pow*5))
done
echo "The Decimal number is: $dec"
34 | P a g e
OUTPUT:

35 | P a g e
WEEK-3

1)
Aim: Write a Program to demonstrate First Come First Serve CPU scheduling
Program:
#include<stdio.h>
int main()
{
int p[10],at[10],bt[10],ct[10],tat[10],wt[10],i,j,temp=0,n;
float awt=0,atat=0;
printf("enter no of proccess you want:");
scanf("%d",&n);
printf("enter %d process:",n);
for(i=0;i<n;i++)
{
scanf("%d",&p[i]);
}
printf("enter %d arrival time:",n);
for(i=0;i<n;i++)
{
scanf("%d",&at[i]);
}
printf("enter %d burst time:",n);
for(i=0;i<n;i++)
{
scanf("%d",&bt[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<(n-i);j++)
{
if(at[j]>at[j+1])
{
temp=p[j+1];
p[j+1]=p[j];
p[j]=temp;
temp=at[j+1];
at[j+1]=at[j];

at[j]=temp;
temp=bt[j+1];
bt[j+1]=bt[j];
bt[j]=temp;
}
}
}
ct[0]=at[0]+bt[0];
for(i=1;i<n;i++)
{
temp=0;
if(ct[i-1]<at[i])
36 | P a g e
{
temp=at[i]-ct[i-1];
}
ct[i]=ct[i-1]+bt[i]+temp;
}
printf("\np\t A.T\t B.T\t C.T\t TAT\t WT");
for(i=0;i<n;i++)
{
tat[i]=ct[i]-at[i];
wt[i]=tat[i]-bt[i];
atat+=tat[i];
awt+=wt[i];
}
atat=atat/n;
awt=awt/n;
for(i=0;i<n;i++)
{
printf("\nP%d\t %d\t %d\t %d \t %d \t %d",p[i],at[i],bt[i],ct[i],tat[i],wt[i]);
}
printf("\naverage turnaround time is %f",atat);

printf("\naverage wating timme is %f\n",awt);


return 0;
}
Output:

2)
Aim: Write a Program to demonstrate Shortest Job First or Shortest Job next CPU scheduling
Program:(preemptive)
#include <stdio.h>
37 | P a g e
int main()
{
int arrival_time[10], burst_time[10], temp[10];
int i, smallest, count = 0, time, limit;
double wait_time = 0, turnaround_time = 0, end;
float average_waiting_time, average_turnaround_time;
printf("\nEnter the Total Number of Processes:\t");
scanf("%d", &limit);
printf("\nEnter Details of %d Processes\n", limit);
for(i = 0; i < limit; i++)
{
printf("\nEnter Arrival Time:\t");
scanf("%d", &arrival_time[i]);
printf("Enter Burst Time:\t");
scanf("%d", &burst_time[i]);
temp[i] = burst_time[i];
}
burst_time[9] = 9999;
for(time = 0; count != limit; time++)
{
smallest = 9;
for(i = 0; i < limit; i++)
{
if(arrival_time[i] <= time && burst_time[i] < burst_time[smallest] && burst_time[i] > 0)
{
smallest = i;
}
}
burst_time[smallest]--;
if(burst_time[smallest] == 0)
{
count++;
end = time + 1;
wait_time = wait_time + end - arrival_time[smallest] - temp[smallest];
turnaround_time = turnaround_time + end - arrival_time[smallest];
}
}
average_waiting_time = wait_time / limit;
average_turnaround_time = turnaround_time / limit;
printf("\n\nAverage Waiting Time:\t%lf\n", average_waiting_time);
printf("Average Turnaround Time:%lf\n", average_turnaround_time);
return 0;
}

Output:

38 | P a g e
Program(non preemptive):
#include<stdio.h>
int main()
{
int bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
float avg_wt,avg_tat;
printf("Enter number of processes:");
scanf("%d",&n);

printf("\nEnter Burst Time:n");


for(i=0;i<n;i++)
{
printf("p%d:",i+1);
scanf("%d",&bt[i]);
p[i]=i+1;
}

//sorting of burst times


for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(bt[j]<bt[pos])
39 | P a g e
pos=j;
}

temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;

temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}

wt[0]=0;

for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];

total+=wt[i];
}

avg_wt=(float)total/n;
total=0;

printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");


for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i];
total+=tat[i];
printf("\np%d\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}

avg_tat=(float)total/n;
printf("\n\nAverage Waiting Time=%f",avg_wt);
printf("\nAverage Turnaround Time=%f\n",avg_tat);
}
Output:

40 | P a g e
3)Aim: Write a Program to demonstrate Round Robin CPU scheduling
Program:
#include<stdio.h>
int main()
{

int i, limit, total = 0, x, counter = 0, time_quantum;


int wait_time = 0, turnaround_time = 0, arrival_time[10], burst_time[10], temp[10];
float average_wait_time, average_turnaround_time;
printf("\nEnter Total Number of Processes:\t");
scanf("%d", &limit);
x = limit;
for(i = 0; i < limit; i++)
{
printf("\nEnter Details of Process[%d]\n", i + 1);

printf("Arrival Time:\t");

scanf("%d", &arrival_time[i]);

printf("Burst Time:\t");

scanf("%d", &burst_time[i]);

temp[i] = burst_time[i];
}

printf("\nEnter Time Quantum:\t");


scanf("%d", &time_quantum);
printf("\nProcess ID\t\tBurst Time\t Turnaround Time\t Waiting Time\n");
for(total = 0, i = 0; x != 0;)
{
if(temp[i] <= time_quantum && temp[i] > 0)
{
total = total + temp[i];
temp[i] = 0;
counter = 1;
}
else if(temp[i] > 0)
{
temp[i] = temp[i] - time_quantum;
total = total + time_quantum;
}
if(temp[i] == 0 && counter == 1)
{
x--;
printf("\nProcess[%d]\t\t%d\t\t %d\t\t\t %d", i + 1, burst_time[i], total - arrival_time[i], total
- arrival_time[i] - burst_time[i]);
wait_time = wait_time + total - arrival_time[i] - burst_time[i];
41 | P a g e
turnaround_time = turnaround_time + total - arrival_time[i];
counter = 0;
}
if(i == limit - 1)
{
i = 0;
}

else if(arrival_time[i + 1] <= total)


{
i++;
}
else
{
i = 0;
}
}

average_wait_time = wait_time * 1.0 / limit;


average_turnaround_time = turnaround_time * 1.0 / limit;
printf("\n\nAverage Waiting Time:\t%f", average_wait_time);
printf("\nAvg Turnaround Time:\t%f\n", average_turnaround_time);
return 0;
}
Output:

42 | P a g e
4) Aim: Write a Program to demonstrate Priority CPU Scheduling
Program(preemptive):
#include<stdio.h>
struct process
{
int WT,AT,BT,TAT,PT;
};

struct process a[10];

int main()
{

int n,temp[10],t,count=0,short_p;
float total_WT=0,total_TAT=0,Avg_WT,Avg_TAT;
printf("Enter the number of the process\n");
scanf("%d",&n);
printf("Enter the arrival time , burst time and priority of the process\n");
printf("AT BT PT\n");
for(int i=0;i<n;i++)
{
scanf("%d%d%d",&a[i].AT,&a[i].BT,&a[i].PT);

// copying the burst time in


// a temp array fot futher use
temp[i]=a[i].BT;
}

// we initialize the burst time


// of a process with maximum
a[9].PT=10000;

for(t=0;count!=n;t++)
{
short_p=9;
for(int i=0;i<n;i++)
{
if(a[short_p].PT>a[i].PT && a[i].AT<=t && a[i].BT>0)
{
short_p=i;
}
}

a[short_p].BT=a[short_p].BT-1;

// if any process is completed


if(a[short_p].BT==0)
{
// one process is completed
43 | P a g e
// so count increases by 1
count++;
a[short_p].WT=t+1-a[short_p].AT-temp[short_p];
a[short_p].TAT=t+1-a[short_p].AT;

// total calculation
total_WT=total_WT+a[short_p].WT;
total_TAT=total_TAT+a[short_p].TAT;

}
}

Avg_WT=total_WT/n;
Avg_TAT=total_TAT/n;

// printing of the answer


printf("ID WT TAT\n");
for(int i=0;i<n;i++)
{
printf("%d %d\t%d\n",i+1,a[i].WT,a[i].TAT);
}

printf("Avg waiting time of the process is %f\n",Avg_WT);


printf("Avg turn around time of the process is %f\n",Avg_TAT);

return 0;
}
Output:

Program(Non preemptive):
#include<stdio.h>
struct process
{
int id,WT,AT,BT,TAT,PR;
};
44 | P a g e
struct process a[10];
// function for swapping
void swap(int *b,int *c)
{
int tem;
tem=*c;
*c=*b;
*b=tem;
}

//Driver function
int main()
{
int n,check_ar=0;

int Cmp_time=0;
float Total_WT=0,Total_TAT=0,Avg_WT,Avg_TAT;
printf("Enter the number of process \n");
scanf("%d",&n);
printf("Enter the Arrival time , Burst time and priority of the process\n");
printf("AT BT PR\n");
for(int i=0;i<n;i++)
{
scanf("%d%d%d",&a[i].AT,&a[i].BT,&a[i].PR);
a[i].id=i+1;
// here we are checking that arrival time
// of the process are same or different
if(i==0)
check_ar=a[i].AT;

if(check_ar!=a[i].AT )
check_ar=1;

}
// if process are arrived at the different time
// then sort the process on the basis of AT
if(check_ar!=0)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(a[j].AT>a[j+1].AT)
{
swap(&a[j].id,&a[j+1].id);
swap(&a[j].AT,&a[j+1].AT);
swap(&a[j].BT,&a[j+1].BT);
swap(&a[j].PR,&a[j+1].PR);
}}}

// logic of Priority scheduling ( non preemptive) algo


45 | P a g e
// if all the process are arrived at different time
if(check_ar!=0)
{
a[0].WT=a[0].AT;
a[0].TAT=a[0].BT-a[0].AT;
// cmp_time for completion time
Cmp_time=a[0].TAT;
Total_WT=Total_WT+a[0].WT;
Total_TAT=Total_TAT+a[0].TAT;
for(int i=1;i<n;i++)
{
int min=a[i].PR;
for(int j=i+1;j<n;j++)
{
if(min>a[j].PR && a[j].AT<=Cmp_time)

{
min=a[j].PR;
swap(&a[i].id,&a[j].id);
swap(&a[i].AT,&a[j].AT);
swap(&a[i].BT,&a[j].BT);
swap(&a[i].PR,&a[j].PR);

}
a[i].WT=Cmp_time-a[i].AT;
Total_WT=Total_WT+a[i].WT;
// completion time of the process
Cmp_time=Cmp_time+a[i].BT;

// Turn Around Time of the process


// compl-Arival
a[i].TAT=Cmp_time-a[i].AT;
Total_TAT=Total_TAT+a[i].TAT;

}
}

// if all the process are arrived at same time


else
{
for(int i=0;i<n;i++)
{
int min=a[i].PR;
for(int j=i+1;j<n;j++)
{
if(min>a[j].PR && a[j].AT<=Cmp_time)
{
min=a[j].PR;
46 | P a g e
swap(&a[i].id,&a[j].id);
swap(&a[i].AT,&a[j].AT);

swap(&a[i].BT,&a[j].BT);
swap(&a[i].PR,&a[j].PR);
}

}
a[i].WT=Cmp_time-a[i].AT;

// completion time of the process


Cmp_time=Cmp_time+a[i].BT;

// Turn Around Time of the process


// compl-Arrival
a[i].TAT=Cmp_time-a[i].AT;
Total_WT=Total_WT+a[i].WT;

Total_TAT=Total_TAT+a[i].TAT;

Avg_WT=Total_WT/n;
Avg_TAT=Total_TAT/n;

// Printing of the results


printf("The process are\n");
printf("ID WT TAT\n");
for(int i=0;i<n;i++)
{
printf("%d\t%d\t%d\n",a[i].id,a[i].WT,a[i].TAT);
}

printf("Avg waiting time is: %f\n",Avg_WT);


printf("Avg turn around time is: %f",Avg_TAT);
return 0;

47 | P a g e
Output:

Week 3:

1. WAP to demonstrate Paging

Ans.

AIM: A program to demonstrate paging

PROCEDURE:
In Operating Systems, Paging is a storage mechanism used to retrieve processes from the secondary
storage into the main memory in the form of pages. The main idea behind the paging is to divide each
process in the form of pages. The main memory will also be divided in the form of frames. One page of
the process is to be stored in one of the frames of the memory. The pages can be stored at the different
locations of the memory but the priority is always to find the contiguous frames or holes. Pages of the
process are brought into the main memory only when they are required otherwise they reside in the
secondary storage. Different operating system defines different frame sizes. The sizes of each frame
must be equal. Considering the fact that the pages are mapped to the frames in Paging, page size needs
to be as same as frame size.

CODE:
#include<stdio.h>
#define MAX 50
int main()
{
int page[MAX],i,n,f,ps,off,pno;
int choice=0;
printf("\nEnter the no of peges in memory: ");
scanf("%d",&n);
printf("\nEnter page size: ");
scanf("%d",&ps);
printf("\nEnter no of frames: ");
scanf("%d",&f);
for(i=0;i<n;i++)
page[i]=-1;
printf("\nEnter the page table\n");
printf("(Enter frame no as -1 if that page is not present in any frame)\n\n");
printf("\npageno\tframeno\n-------\t-------");
for(i=0;i<n;i++)
48 | P a g e
{
printf("\n\n%d\t\t",i);
scanf("%d",&page[i]);
}
do
{
printf("\n\nEnter the logical address(i.e,page no & offset):");
scanf("%d%d",&pno,&off);
if(page[pno]==-1)
printf("\n\nThe required page is not available in any of frames");
else
printf("\n\nPhysical address(i.e,frame no & offset):%d,%d",page[pno],off);
printf("\nDo you want to continue(1/0)?:");
scanf("%d",&choice);
}while(choice==1);
return 1;
}

OUTPUT:

2. WAP to demonstrate segmentation

Ans.

AIM: A program to demonstrate segmentation

PROCEDURE:
Segmentation is a memory management technique that splits up the virtual address space of an
application into chunks. By splitting the memory up into manageable chunks, the operating system can
track which parts of the memory are in use and which parts are free. This makes allocating and
deallocating memory much faster and simpler for the operating system. The segments are of unequal
49 | P a g e
size and are not placed in a contiguous way. As it’s a non-contiguous memory allocation technique,
internal fragmentation doesn’t occur. The length is decided on the base of the purpose of the segment in
a user program. Segmentation is a memory management technique which divides the program from the
user’s view of memory. That means the program is divided into modules/segments, unlike paging in
which the program was divided into different pages, and those pages may or may not be loaded into the
memory simultaneously. Segmentation prevents internal fragmentation.

CODE:
#include<stdio.h>
int main()
{
int a[10][10],b[100],i,j,n,x,base,size,seg,off;
printf("Enter the segments count\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{

printf("Enter the %d size \n",i+1);


scanf("%d",&size);
a[i][0]=size;
printf("Enter the base address\n");
scanf("%d",&base);
a[i][1]=base;

for(j=0;j<size;j++)
{
x=0;
scanf("%d",&x);
// b[base]=x;
base++;
b[base]=x;
}
}
printf("Enter the segment number and offset value \n");
scanf("%d%d",&seg,&off);
if(off<a[seg][0])
{
int abs=a[seg][1]+off;
printf("the offset is less tha %d",a[seg][0]);
printf("\n %d + %d = %d\n",a[seg][1],off,abs);
printf("the element %d is at %d ",b[abs+1],abs);
}
else
{
printf("Error in locating\n");
}
}

OUTPUT:

50 | P a g e
Week 4:

1. WAP to demonstrate the Linked File allocation techniques


Ans.
AIM: A program to demonstrate the Linked File allocation techniques
PROCEDURE:
It is easy to allocate the files because allocation is on an individual block basis. Each block contains a
pointer to the next free block in the chain. Here also the file allocation table consisting of a single entry
for each file. Using this strategy any free block can be added to a chain very easily. There is a link
between one block to another block, that’s why it is said to be linked allocation. We can avoid the
external fragmentation.
Algorithm for Linked File Allocation:
Step 1: Create a queue to hold all pages in memory
Step 2: When the page is required replace the page at the head of the queue
Step 3: Now the new page is inserted at the tail of the queue
Step 4: Create a stack
Step 5: When the page fault occurs replace page present at the bottom of the stack
Step 6: Stop the allocation.
CODE:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int f[50], p,i, st, len, j, c, k, a;
//clrscr();
for(i=0;i<50;i++)
f[i]=0;
printf("Enter how many blocks already allocated: ");
scanf("%d",&p);
printf("Enter blocks already allocated: ");
for(i=0;i<p;i++)
{

51 | P a g e
scanf("%d",&a);
f[a]=1;
}
x: printf("Enter index starting block and length: ");
scanf("%d%d", &st,&len);
k=len;
if(f[st]==0)
{
for(j=st;j<(st+k);j++)
{
if(f[j]==0)
{
f[j]=1;
printf("%d-------->%d\n",j,f[j]);
}
else
{
printf("%d Block is already allocated \n",j);
k++;
}

}
}
else
printf("%d starting block is already allocated \n",st);
printf("Do you want to enter more file(Yes - 1/No - 0)");
scanf("%d", &c);
if(c==1)
goto x;
else
exit(0);
return 0;
}
OUTPUT:

2. WAP to demonstrate Indexed file allocation techniques


Ans.
AIM: A program to demonstrate Indexed file allocation techniques
52 | P a g e
PROCEDURE:
Indexed allocation supports both sequential and direct access files. The file indexes are not physically
stored as a part of the file allocation table. Whenever the file size increases, we can easily add some
more blocks to the index. In this strategy, the file allocation table contains a single entry for each file.
The entry consisting of one index block, the index blocks having the pointers to the other blocks. No
external fragmentation.
Algorithm for Indexed File Allocation:
Step 1: Start.
Step 2: Let n be the size of the buffer
Step 3: check if there are any producer
Step 4: if yes check whether the buffer is full
Step 5: If no the producer item is stored in the buffer
Step 6: If the buffer is full the producer has to wait
Step 7: Check there is any consumer.If yes check whether the buffer is empty
Step 8: If no the consumer consumes them from the buffer
Step 9: If the buffer is empty, the consumer has to wait.
Step 10: Repeat checking for the producer and consumer till required
Step 11: Terminate the process.

CODE:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

int main()
{
int f[50], index[50],i, n, st, len, j, c, k, ind,count=0;
//clrscr();
for(i=0;i<50;i++)
f[i]=0;
x:printf("Enter the index block: ");
scanf("%d",&ind);
if(f[ind]!=1)
{
printf("Enter no of blocks needed and no of files for the index %d on the disk : \n", ind);
scanf("%d",&n);
}
else
{
printf("%d index is already allocated \n",ind);
goto x;
}
y: count=0;
for(i=0;i<n;i++)
{
scanf("%d", &index[i]);
if(f[index[i]]==0)
count++;
}
if(count==n)
{
for(j=0;j<n;j++)
53 | P a g e
f[index[j]]=1;
printf("Allocated\n");
printf("File Indexed\n");
for(k=0;k<n;k++)
printf("%d-------->%d : %d\n",ind,index[k],f[index[k]]);
}
else
{
printf("File in the index is already allocated \n");
printf("Enter another file indexed");
goto y;
}
printf("Do you want to enter more file(Yes - 1/No - 0)");
scanf("%d", &c);
if(c==1)
goto x;
else
exit(0);
return 0;
}

OUTPUT:

3. WAP to demonstrate the contiguous file allocation techniques.


Ans.
AIM: A program to demonstrate the contiguous file allocation techniques.
PROCEDURE:
In this allocation strategy, each file occupies a set of contiguously blocks on the disk. This strategy is
best suited. For sequential files, the file allocation table consists of a single entry for each file. It shows
the filenames, starting block of the file and size of the file. The main problem with this strategy is, it is
difficult to find the contiguous free blocks in the disk and some free blocks could happen between two
54 | P a g e
files.
Algorithm for Sequential File Allocation:
Step 1: Start the program.
Step 2: Get the number of memory partition and their sizes.
Step 3: Get the number of processes and values of block size for each process.
Step 4: First fit algorithm searches all the entire memory block until a hole which is big enough is
encountered. It allocates that memory block for the requesting process.
Step 5: Best-fit algorithm searches the memory blocks for the smallest hole which can be allocated to
requesting process and allocates it.
Step 6: Worst fit algorithm searches the memory blocks for the largest hole and allocates it to the
process.
Step 7: Analyses all the three memory management techniques and display the best algorithm which
utilizes the memory resources effectively and efficiently.
Step 8: Stop the program.
CODE:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

int main()
{
int f[50], i, st, len, j, c, k, count = 0;
//clrscr();
for(i=0;i<50;i++)
f[i]=0;
printf("Files Allocated are : \n");
x: count=0;
printf("Enter starting block and length of files: ");
scanf("%d%d", &st,&len);
for(k=st;k<(st+len);k++)
if(f[k]==0)
count++;
if(len==count)
{
for(j=st;j<(st+len);j++)
if(f[j]==0)
{
f[j]=1;
printf("%d\t%d\n",j,f[j]);
}
if(j!=(st+len-1))
printf(" The file is allocated to disk\n");
}
else
printf(" The file is not allocated \n");
printf("Do you want to enter more file(Yes - 1/No - 0)");
scanf("%d", &c);
if(c==1)
goto x;
else
exit(0);
return 0;
}
55 | P a g e
OUTPUT:

56 | P a g e
Week-5
1.
Aim: Demostrate System calls with simple example Program.

Program:
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
int main( ){
pid_t child_pid;
child_pid = fork (); // Create a new child process;
if (child_pid < 0) {
printf("fork failed");
return 1;
} else if (child_pid == 0) {
printf ("child process successfully created!\n");
printf ("child_PID = %d,parent_PID = %d\n",
getpid(), getppid( ) );
} else {
// wait(NULL);
printf ("parent process successfully created!\n");
printf ("child_PID = %d, parent_PID = %d", getpid( ), getppid( ) );
}
return 0;
}
OUTPUT:

2.
Aim: Demostrate following I/O system calls with examples
(Reference Text book : Begining Linux Progrogramming Programmer to Programmer )
i) open
ii) read
iii) Write
iv)lseek
v)ioctl
vi)stat
vi)syn
Program:
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdlib.h>
#include<sys/ioctl.h>
#include<sys/stat.h>
#define WR_VALUE _IOW('a','a',int*)
#define RD_VALUE _IOR('a','b',int*)
int main()
{
// if file does not have in directory
// then file foo.txt is created.
int fd = open("sample.txt", O_RDONLY | O_CREAT);
int fd2 = open("file2.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
57 | P a g e
int fd3 = open("file3.txt", O_RDWR);
char c[20];
// reading from sample.txt
read(fd, &c, 20);
printf("Text in file is: %s\n",c);
//writing into file2.txt which was stored in c
write(fd2, c, read(fd, &c, 20));
lseek(fd, 5, SEEK_CUR);
char c1[20];
read(fd, &c1, 20);
printf("Text after lseek 10 characters: %s",c1);
printf("Enter a value to write in the file: ");
int number;
scanf("%d",&number);
ioctl(fd3, WR_VALUE,(int*) &number);
struct stat sfile;
stat("stat.c", &sfile);
printf("st_mode = %o\n",sfile.st_mode);
close(fd);
close(fd2);
close(fd3);
return 0;
}
OUTPUT:

3.
Aim: Demonstrate following File system call with examples
i) link, ii) unlink

58 | P a g e
iii) mount

iv)unmount

v) chmod

vi) chown

4.
Aim: Demonstrate how process is created and allocate memory in /proc folder with example Program.
Program:
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc, char *argv[])
{
int a;
int fd1=open("kk.txt",O_RDONLY,742); //open system call

59 | P a g e
int fd2=open("kk1.txt",O_RDONLY,S_IRWXU|S_IRGRP|S_IXOTH);
printf(" fd1=%d,fd2=%d\n", fd1,fd2);
printf("Process Id=%d\n",getpid());
scanf("%d",&a);
}
OUTPUT:
Process Program execution output:

Proc folder showing creation of new processes output:


ls:

proc ls:

ls:

60 | P a g e
WEEK – 5

1.
Aim: Demonstrate System calls with
simple example Program

Program:
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include <stdlib.h>
int main()
{
printf(" Before fork");
int
fd1=open("kk.txt",O_RDONLY,742); //
kk.txt is a shared resource to parent and
child process
int a; // a is shared variable to
parent and child process
printf(" Process Id of parent %d \
n",getpid());
int rf=fork();
if(rf==0) // Upon successful
execution fork() --> Child process will
execute below code in if block
{
printf("Inside child process \n");
printf(" Process Id of child pid=
%d rf=%d \n ",getpid(),rf);
scanf("%d",&a);
printf(" Inside child a value is a=
%d",a);

}
else if (rf> 0) // Upon successful
execution fork() system call --> Parent
process will exceute below code in elseif
block
{
printf("Inside parent process");
printf(" Process Id of parent pid=%d
rf=%d \n",getpid(),rf);
scanf("%d",&a);
printf(" Inside parent a value is a=
%d",a);
}
else{ // Upon uncusccessful
execution fork() system call Parent
process will exceute below code in else
block
61 | P a g e
printf(" Fork unsucessful \n Indide
parent and Process Id of parent pid= %d
rf=%d \n ",getpid(),rf);
}
printf("End of process %d",
getpid());
return 0;
}
OUTPUT:

In proc folder:

2.
Aim: Write a Programt to demonstrate the use of exec system calls
Parent process --> Execute factorial of given number
Child process --> Execute prime number
PROGRAM :
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include <stdlib.h>

int main()
{
printf(" Before fork");
int
fd1=open("kk.txt",O_RDONLY,742); //
kk.txt is a shared resource to parent and
child process
int a; // a is shared variable to
parent and child process
printf(" Process Id of parent %d \
n",getpid());
int rf=fork();

if(rf==0) // Upon successful


execution fork() --> Child process will
execute below code in if block

62 | P a g e
{
printf("Inside child process \n");
printf(" Process Id of child pid=
%d rf=%d \n ",getpid(),rf);
printf("Child process: to execute
the prime number Program\nEnter a
number: ");
scanf("%d",&a);
int flag = 0;
for(int i=2;i<=a/2;i++){
if (a%i==0){
flag=1;
break;
}
}
if(flag==0){
printf("Given number %d is a
prime number\n",a);
}
else{
printf("Given number %d is not a
prime number\n",a);
}
}
else if (rf> 0) // Upon successful
execution fork() system call --> Parent
process will exceute below code in elseif
block
{
printf("Inside parent process");
printf(" Process Id of parent pid=%d
rf=%d \n",getpid(),rf);
printf("Parent process: to execute the
factorial of a number\nEnter a number:
");
scanf("%d",&a);
int total = 1, i = 1;
while(i<=a){
total=total*i;
i=i+1;
}
printf("Factorial value is: %d\
n",total);
}
else{ // Upon uncusccessful
execution fork() system call Parent
process will exceute below code in else
block
printf(" Fork unsucessful \n
Indide parent and Process Id of parent

63 | P a g e
pid= %d rf=%d \n ",getpid(),rf);
}
printf("End of process %d\n",
getpid());
return 0;
}
OUTPUT:

3.
Aim:
Write a program to demonstrate use following exe functions
i. int execl(const char* path,
const char* arg, …)
ii. int execlp(const char* file,
const char* arg, …)
iii. int execle(const char* path,
const char* arg, …, char*
const envp[])
iv. int execv(const char* path,
const char* argv[])
v. int execvp(const char* file,
const char* argv[])
vi. int execvpe(const char* file,
const char* argv[], char
*const envp[])

Program:
Exec.c
#include<stdio.h>
#include<unistd.h>
int main()
{
int i;
printf("I am Demo file called by
execvp() ");
printf("\n");
return 0;
}

64 | P a g e
Execv.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
char *args[]={"./exec",NULL};
execv(args[0],args);
printf("Ending-----");
return 0;
}
Output:

Execvp.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
char
*args[]={"./3_6_demo",NULL};
execvp(args[0],args);
printf("Ending-----");
return 0;
}
Output:

4.
Aim: Write a Program to demonstrate the
use of vfork()

PROGRAM :
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include <stdlib.h>

int main()
{
printf(" Before fork");
int
fd1=open("kk.txt",O_RDONLY,742); //
kk.txt is a shared resource to parent and

65 | P a g e
child process
int a,b; // a is shared variable to
parent and child process
printf(" Process Id of parent %d \
n",getpid());
int rf=vfork();
if(rf==0) // Upon successful
execution fork() --> Child process will
execute below code in if block
{
printf("Inside child process \n");
printf(" Process Id of child pid=
%d rf=%d \n ",getpid(),rf);
scanf("%d",&b);
printf(" Inside child b value is b=
%d",b);

else if (rf> 0) // Upon successful


execution fork() system call --> Parent
process will exceute below code in elseif
block
{

printf("Inside parent process");


printf(" Process Id of parent pid=%d
rf=%d \n",getpid(),rf);
scanf("%d",&a);
printf(" Inside parent a value is a=
%d",a);
}
else{ // Upon uncusccessful
execution fork() system call Parent
process will exceute below code in else
block
printf(" Fork unsucessful \n
Indide parent and Process Id of parent
pid= %d rf=%d \n ",getpid(),rf);
}
printf("End of process %d\n",
getpid());
return 0;
}

OUTPUT:
66 | P a g e
5. Aim: Write a Program to demonstrate
Orphan process

PROGRAM :
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
// Create a child process
int pid = fork();

if (pid > 0)
printf("in parent process\n");

// Note that pid is 0 in child process


// and negative if fork() fails
else if (pid == 0)
{
sleep(9);
printf("in child process\n");
}
OUTPUT:

6.
Aim: Write a Program to demonstrate
Zombie process

PROGRAM :
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#include <stdio.h>
int main()
67 | P a g e
{
pid_t pid;
char *message;
int n;
int exit_code;
printf("fork Program starting\n");
pid = fork();
switch(pid)
{
case -1:
perror("fork failed");
exit(1);
case 0:
message = "This is the child";
n = 3;
exit_code = 37;
break;
default:
message = "This is the parent";
n = 5;
exit_code = 0;
break;
}
for(; n > 0; n--) {
puts(message);
sleep(1);
}
}
OUTPUT:

68 | P a g e
WEEK 6

Program 1
Aim: Write a Program to demonstrate the use of atexit() exit handler

Program :
#include <stdio.h>
#include <stdlib.h>
#include<fcntl.h>
#include<unistd.h>

//File Discriptors
int fd1;
int fd2;

void functionA () { // Exit Handler


close(fd1);
printf("We are in functionA and closed the file \n");
}

void functionB () { // Exit Handler


close(fd2);
printf("We are in functionB and closed the file \n");
}
69 | P a g e
int main () {
/* register the termination function */
char buf[10];
fd1=open("kk.txt",O_RDONLY,742); // kk.txt should present in current folder
fd2=open("kk1.txt",O_RDONLY,S_IRWXU|S_IRGRP|S_IXOTH);

read(fd1,buf,10);
write(1,buf,10);
printf("\nCompleted the operation A \n");
atexit(functionA );

read(fd2,buf,10);
write(1,buf,10);
printf("\nCompleted the operation B \n");
atexit(functionB );

printf("Starting main Program...\n");

printf("Exiting main Program...\n");

return(0);
}

Output:

Program 2

Aim: Write a Program to demonstrate the use of exit() and _exit() system call

Program :

i)use of exit():
#include<stdio.h>
#include<stdlib.h>

70 | P a g e
void func(){
printf("Exiting\n");
}
int main(){
atexit(func);
exit(10);
}

ii)use of _exit():
#include<stdio.h>
#include<stdlib.h>

void func(){
printf("Exiting\n");
}
int main(){
printf("Start of the Program\n");
atexit(func);
_Exit(10);
printf("End of the Program\n");
}
Output:
Exit():

_exit():

Program 3

Aim: Write a Program to demonstrate the use of wait() , waitpid() and waitid()

Program:

Wait() function:
#define _POSIX_SOURCE
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include<stdlib.h>
#include <time.h>
int main() {
pid_t pid;
time_t t;
71 | P a g e
int status;
if ((pid = fork()) < 0)
perror("fork() error");
else if (pid == 0) {
time(&t);
printf("child (pid %d) started at %s", (int) getpid(), ctime(&t));
sleep(5);
time(&t);
printf("child exiting at %s", ctime(&t));
exit(42);
}
else {
printf("parent has forked child with pid of %d\n", (int) pid);
time(&t);
printf("parent is starting wait at %s", ctime(&t));
if ((pid = wait(&status)) == -1)
perror("wait() error");
else {
time(&t);
printf("parent is done waiting at %s", ctime(&t));
printf("the pid of the process that ended was %d\n", (int) pid);
if (WIFEXITED(status))
printf("child exited with status of %d\n", WEXITSTATUS(status));
else if (WIFSIGNALED(status))
printf("child was terminated by signal %d\n",
WTERMSIG(status));
else if (WIFSTOPPED(status))
printf("child was stopped by signal %d\n", WSTOPSIG(status));
else puts("reason unknown for child termination");

}
}

Output:

Waitpid() function:
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

int
72 | P a g e
main(int argc, char *argv[])
{
pid_t cpid, w;
int status;

cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}

if (cpid == 0) { /* Code executed by child */


printf("Child PID is %ld\n", (long) getpid());
if (argc == 1)
pause(); /* Wait for signals */
_exit(atoi(argv[1]));

} else { /* Code executed by parent */


do {
w = waitpid(cpid, &status, WUNTRACED | WCONTINUED);
if (w == -1) {
perror("waitpid");
exit(EXIT_FAILURE);
}

if (WIFEXITED(status)) {
printf("exited, status=%d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("killed by signal %d\n", WTERMSIG(status));

} else if (WIFSTOPPED(status)) {

printf("stopped by signal %d\n", WSTOPSIG(status));

} else if (WIFCONTINUED(status)) {
printf("continued\n");
}
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
exit(EXIT_SUCCESS);
}
}

Output:
Terminal 1

Terminal 2

73 | P a g e
Waitid() function:
#define pr_exit(n) printf("%d\n", n)
#define err_sys perror
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
int main(void)
{
pid_t pid;
int status;
siginfo_t info;

if ((pid = fork()) < 0)


err_sys("fork error");
else if (pid == 0) /* child */
exit(7);
if (waitid(P_PID,pid,&info,WEXITED) != pid) /* wait for child */

err_sys("wait error");
pr_exit(status); /* and print its status */
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid == 0) /* child */
abort(); /* generates SIGABRT */
if (waitid(P_PID,pid,&info,WEXITED) != pid) /* wait for child */
err_sys("wait error");
pr_exit(status); /* and print its status */
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid == 0) /* child */
status = 0; /* divide by 0 generates SIGFPE */
if (waitid(P_PID,pid,&info,WEXITED) != pid) /* wait for child */

74 | P a g e
err_sys("wait error");
pr_exit(status);
exit(0);
}
Output:

Program 4

Aim: Write a Program to demonstrate the use of wait3() and wait4()

Program:
Wait3() function:
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/resource.h>
int
main(int argc, char *argv[])

{
pid_t cpid, w;
int status;
struct rusage Use;
cpid = fork();
if (cpid == -1) {
perror("fork");

exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Code executed by child */
printf("Child PID is %ld\n", (long) getpid());
if (argc == 1)
pause(); /* Wait for signals */
_exit(atoi(argv[1]));
} else { /* Code executed by parent */
do {
w = wait3(&status, WUNTRACED | WCONTINUED, &Use);
if (w == -1) {
perror("waitpid");
exit(EXIT_FAILURE);
75 | P a g e
}
if (WIFEXITED(status)) {
printf("exited, status=%d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("killed by signal %d\n", WTERMSIG(status));
} else if (WIFSTOPPED(status)) {
printf("stopped by signal %d\n", WSTOPSIG(status));
} else if (WIFCONTINUED(status)) {
printf("continued\n");
}
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
exit(EXIT_SUCCESS);
}

Output:
Terminal 1

Terminal 2

Wait4() function:
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/resource.h>

int
main(int argc, char *argv[])
{
pid_t cpid, w;
int status;
76 | P a g e
struct rusage Use;

cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}

if (cpid == 0) { /* Code executed by child */


printf("Child PID is %ld\n", (long) getpid());
if (argc == 1)
pause(); /* Wait for signals */
_exit(atoi(argv[1]));

} else { /* Code executed by parent */


do {
w = wait4(cpid, &status, WUNTRACED | WCONTINUED, &Use);
if (w == -1) {
perror("waitpid");
exit(EXIT_FAILURE);
}

if (WIFEXITED(status)) {
printf("exited, status=%d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("killed by signal %d\n", WTERMSIG(status));
} else if (WIFSTOPPED(status)) {
printf("stopped by signal %d\n", WSTOPSIG(status));
} else if (WIFCONTINUED(status)) {
printf("continued\n");
}
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
exit(EXIT_SUCCESS);
}
}

Output:
Terminal 1

Teminal 2

77 | P a g e
Week – 7

1. WAP to demonstrate Banker’s algorithm (Resource Allocation)

AIM: A program to demonstrate Banker’s algorithm (Resource Allocation)

PROCEDURE:
It is a banker algorithm used to avoid deadlock and allocate resources safely to each process in the
computer system. The 'S-State' examines all possible tests or activities before deciding whether the
allocation should be allowed to each process. It also helps the operating system to successfully share the
resources between all the processes. The banker's algorithm is named because it checks whether a
person should be sanctioned a loan amount or not to help the bank system safely simulate allocation
resources. For example, suppose the number of account holders in a particular bank is 'n', and the total
money in a bank is 'T'. If an account holder applies for a loan; first, the bank subtracts the loan amount
from full cash and then estimates the cash difference is greater than T to approve the loan amount.
These steps are taken because if another person applies for a loan or withdraws some amount from the
bank, it helps the bank manage and operate all things without any restriction in the functionality of the
banking system.
Similarly, it works in an operating system. When a new process is created in a computer system, the
process must provide all types of information to the operating system like upcoming processes, requests
for their resources, counting them, and delays. Based on these criteria, the operating system decides
which process sequence should be executed or waited so that no deadlock occurs in a system. Therefore,
it is also known as deadlock avoidance algorithm or deadlock detection in the operating system.

CODE:
#include <stdio.h>
int main()
{
int Max[10][10], need[10][10], alloc[10][10], avail[10], completed[10], safeSequence[10];
int p, r, i, j, process, count;
count = 0;
printf("Enter the no of processes : ");
scanf("%d", &p);
for(i = 0; i< p; i++)
completed[i] = 0;
printf("\n\nEnter the no of resources : ");
scanf("%d", &r);
printf("\n\nEnter the Max Matrix for each process : ");
for(i = 0; i < p; i++)
78 | P a g e
{
printf("\nFor process %d : ", i + 1);
for(j = 0; j < r; j++)
scanf("%d", &Max[i][j]);
}
printf("\n\nEnter the allocation for each process : ");
for(i = 0; i < p; i++)
{
printf("\nFor process %d : ",i + 1);
for(j = 0; j < r; j++)
scanf("%d", &alloc[i][j]);
}
printf("\n\nEnter the Available Resources : ");
for(i = 0; i < r; i++)
scanf("%d", &avail[i]);
for(i = 0; i < p; i++)

for(j = 0; j < r; j++)


need[i][j] = Max[i][j] - alloc[i][j];
do
{
printf("\n Max matrix:\tAllocation matrix:\n");
for(i = 0; i < p; i++)
{
for( j = 0; j < r; j++)
printf("%d ", Max[i][j]);
printf("\t\t");
for( j = 0; j < r; j++)
printf("%d ", alloc[i][j]);
printf("\n");
}
process = -1;
for(i = 0; i < p; i++)
{
if(completed[i] == 0)//if not completed
{
process = i ;
for(j = 0; j < r; j++)
{
if(avail[j] < need[i][j])
{
process = -1;
break;
}
}
}
if(process != -1)
break;
}
if(process != -1)
{
printf("\nProcess %d runs to completion!", process + 1);
safeSequence[count] = process + 1;
count++;
79 | P a g e
for(j = 0; j < r; j++)
{
avail[j] += alloc[process][j];
alloc[process][j] = 0;
Max[process][j] = 0;
completed[process] = 1;
}
}
}while(count != p && process != -1);
if(count == p)
{
printf("\nThe system is in a safe state!!\n");
printf("Safe Sequence : < ");
for( i = 0; i < p; i++)
printf("%d ", safeSequence[i]);
printf(">\n");

}
else
printf("\nThe system is in an unsafe state!!");
}

OUTPUT:

80 | P a g e
2. Demonstration of Bankers Algorithm for Deadlock Avoidance.

Python3 program to illustrate


# Banker's Algorithm

# Number of processes
P=5

# Number of resources
R=3

# Function to find the need of each process


def calculateNeed(need, maxm, allot):

# Calculating Need of each P


for i in range(P):
for j in range(R):

# Need of instance = maxm instance -


# allocated instance
need[i][j] = maxm[i][j] - allot[i][j]

# Function to find the system is in


# safe state or not
def isSafe(processes, avail, maxm, allot):
need = [ ]
for i in range(P):
l=[]
for j in range(R):
l.append(0)
need.append(l)

# Function to calculate need matrix


calculateNeed(need, maxm, allot)

81 | P a g e
# Mark all processes as infinish
finish = [0] * P

# To store safe sequence


safeSeq = [0] * P

# Make a copy of available resources


work = [0] * R
for i in range(R):
work[i] = avail[i]

# While all processes are not finished


# or system is not in safe state.
count = 0
while (count < P):

# Find a process which is not finish


# and whose needs can be satisfied
# with current work[ ] resources.
found = False
for p in range(P):

# First check if a process is finished,


# if no, go for next condition
if (finish[p] == 0):

# Check if for all resources


# of current P need is less
# than work
for j in range(R):
if (need[p][j] > work[j]):
break

# If all needs of p were satisfied.


if (j == R - 1):

# Add the allocated resources of


# current P to the available/work
# resources i.e.free the resources
for k in range(R):
work[k] += allot[p][k]

# Add this process to safe sequence.


safeSeq[count] = p
count += 1

# Mark this p as finished


finish[p] = 1

found = True

# If we could not find a next process


# in safe sequence.

82 | P a g e
if (found == False):
print("System is not in safe state")
return False

# If system is in safe state then


# safe sequence will be as below
print("System is in safe state.",
"\nSafe sequence is: ", end = " ")
print(*safeSeq)

return True

# Driver code
if __name__ =="__main__":

processes = [0, 1, 2, 3, 4]

# Available instances of resources


avail = [3, 3, 2]

# Maximum R that can be allocated


# to processes
maxm = [[7, 5, 3], [3, 2, 2],
[9, 0, 2], [2, 2, 2],
[4, 3, 3]]

# Resources allocated to processes


allot = [[0, 1, 0], [2, 0, 0],
[3, 0, 2], [2, 1, 1],
[0, 0, 2]]

# Check system is in safe state or not


isSafe(processes, avail, maxm, allot)

# This code is contributed by


# Shubham Singh(SHUBHAMSINGH10)

Output:
System is in safe state.
Safe sequence is: 1 3 4 0 2

83 | P a g e
Week – 8

1. WAP program to demonstrate the use of setuid(), setgid() system calls and sticky bit.

Ans.

AIM: A program to demonstrate the user of setuid(), setgid() and sticky bit system calls

PROCEDURE:
Setuid(): This bit is present for files which have executable permissions. The setuid bit simply indicates
that when running the executable, it will set its permissions to that of the user who created it (owner),
instead of setting it to the user who launched it. Similarly, there is a setgid bit which does the same for
the gid.
To locate the setuid, look for an ‘s’ instead of an ‘x’ in the executable bit of the file permissions.
Setgid(): The setgid affects both files as well as directories. When used on a file, it executes with the
privileges of the group of the user who owns it instead of executing with those of the group of the user
Who executed it.

When the bit is set for a directory, the set of files in that directory will have the same group as the group
of the parent directory, and not that of the user who created those files. This is used for file sharing since
they can be now modified by all the users who are part of the group of the parent directory.
To locate the setgid bit, look for an ‘s’ in the group section of the file permissions
Sticky bit: The sticky bit was initially introduced to ‘stick’ an executable program’s text segment in the
swap space even after the program has completed execution, to speed up the subsequent runs of the
same program. However, these days the sticky bit means something entirely different.
When a directory has the sticky bit set, its files can be deleted or renamed only by the file owner,
directory owner and the root user. Simply look for a ‘t’ character in the file permissions to locate the
sticky bit. The snippet below shows how we can set the sticky bit for some directory “Gatos”, and how
it prevents the new user from deleting a file in the directory.

CODE:
1. Setuid()
Setting a user set bit using ‘chmod u+s <filename’ command

Creating a new user and checking him in /etc/passwd (in users file)

84 | P a g e
Switching to other user and trying to modify the file which has the set bit turned on

2. Sticky bit
Creating a directory and making its sticky bit on by command ‘chmod +t <filename>’

Switching to other user and modifying the files

3. Setgid()
Setting gid using command ‘chmod g+s <filename>’ and checking to modify from other user

85 | P a g e
2. WAP program to demonstrate the use of setuid(), setguid(), seteuid(), getgid(), geteuid(),
getegid()

Ans.

AIM: Program to demonstrate the use of setuid(), setgid(), seteuid(), getgid(), geteuid(), getegid()

PROCEDURE:
Setuid(): This bit is present for files which have executable permissions. The setuid bit simply indicates
that when running the executable, it will set its permissions to that of the user who created it (owner),
instead of setting it to the user who launched it. Similarly, there is a setgid bit which does the same for
the gid.
To locate the setuid, look for an ‘s’ instead of an ‘x’ in the executable bit of the file permissions.
Setgid(): The setgid affects both files as well as directories. When used on a file, it executes with the
privileges of the group of the user who owns it instead of executing with those of the group of the user
Who executed it.

When the bit is set for a directory, the set of files in that directory will have the same group as the group
of the parent directory, and not that of the user who created those files. This is used for file sharing since
they can be now modified by all the users who are part of the group of the parent directory.
To locate the setgid bit, look for an ‘s’ in the group section of the file permissions
Seteuid(): The process effective user ID is reset if the UID parameter is equal to either the current real
or saved user IDs or if the effective user ID of the process is the root user.
Getgid(): The getuid subroutine returns the real user ID of the current process.
Geteuid(): The geteuid subroutine returns the effective user ID of the current process.
Getegid(): The getegid subroutine returns the effective group ID of the current process.

CODE:
#include<stdio.h>
#include<unistd.h>

int main()
{
uid_t uid;
printf("Before setting the uid and gid\nreal user id: %d\nreal grp id: %d\neffective user id: %d\
neffective grp id: %d\n",getuid(),getgid(),geteuid(),getegid());
setuid(1003);
setgid(1002);
printf("After setting the uid and gid\nreal user id: %d\nreal grp id: %d\neffective user id: %d\
neffective grp id: %d\n",getuid(),getgid(),geteuid(),getegid());

86 | P a g e
return 0;
}

OUTPUT:

3. WAP to demonstrate the use of set setresuid(), setresgid(), setfsuid() and setfsgid()

Ans.

AIM: A program to demonstrate the use of setresuid(), setresgid(), setfsuid() and setfsgid()

PROCEDURE:
Setresuid(): setresuid() sets the real user ID, the effective user ID, and the saved set-user-ID of the
calling process. An unprivileged process may change its real UID, effective UID, and saved set-user-ID,
each to one of: the current real UID, the current effective UID, or the current saved set-user-ID
Setresgid(): setresgid() sets the real GID, effective GID, and saved set-group-ID of the calling process
(and always modifies the file system GID to be the same as the effective GID), with the same
restrictions for unprivileged processes.
Setfsuid(): The system call setfsuid() sets the user ID that the Linux kernel uses to check for all
accesses to the file system. Normally, the value of fsuid will shadow the value of the effective user ID.
In fact, whenever the effective user ID is changed, fsuid will also be changed to the new value of the
effective user ID.
Setfsgid(): The system call setfsgid() sets the group ID that the Linux kernel uses to check for all
accesses to the file system. Normally, the value of fsgid will shadow the value of the effective group ID.
In fact, whenever the effective group ID is changed, fsgid will also be changed to the new value of the
effective group ID.

CODE:
#include<stdio.h>
#include<unistd.h>

int main()
{
uid_t uid;
printf("Before setting the uid and gid\nreal user id: %d\nreal grp id: %d\neffective user id: %d\
neffective grp id: %d\n",getuid(),getgid(),geteuid(),getegid());
setresuid(1001,1001,1001);
setresgid(1002,1002,1002);
printf("After using resuid and resgid\nreal user id: %d\nreal grp id: %d\neffective user id: %d\
neffective grp id: %d\n",getuid(),getgid(),geteuid(),getegid());
87 | P a g e
setfsuid(1001);

setfsgid(1002);

printf("After using fsuid and fsgid\nreal user id: %d\nreal grp id: %d\neffective user id:

%d\neffective grp id: %d\n",getuid(),getgid(),geteuid(),getegid());


return 0;
}

OUTPUT:

4. Write the difference between


a. Effective user ID
b. Effective group ID
c. Real user ID
d. Real group ID
e. File system user ID
f. File system group ID

Effective user ID and Effective Group ID


In Unix the effective user ID and group ID, in conjunction with the supplementary group IDs, are used
to determine the permissions granted to a process when it tries to perform various operations (i.e.,
system calls). For example, these identifiers determine the permissions granted to a process when it
accesses resources such as files and System V interprocess communication (IPC) objects, which
themselves have associated user and group IDs determining to whom they belong. A process whose
effective user ID is 0 (the user ID of root) has all of the privileges of the super user. Such a process is
referred to as a privileged process. Certain system calls can be executed only by privileged processes
Real user ID and Real group ID
The real user ID and group ID identify the user and group to which the process belongs. As part of the
login process, a login shell gets its real user and group IDs from the third and fourth fields of the user’s
88 | P a g e
password record in the /etc/passwd file. When a new process is created (e.g., when the shell executes a

program), it inherits these identifiers from its parent.


File system user ID and File system group ID
On Linux, it is the file-system user and group IDs, rather than the effective user and group IDs, that are

used (in conjunction with the supplementary group IDs) to determine permissions when performing file-
system operations such as opening files, changing file ownership, and modifying file permissions.
Normally, the file-system user and group IDs have the same values as the corresponding effective IDs
(and thus typically are the same as the corresponding real IDs). Furthermore, whenever the effective
user or group ID is changed, either by a system call or by execution of a set-user-ID or set-group-ID
program, the corresponding file-system ID is also changed to the same value

89 | P a g e
90 | P a g e
Week – 10

4. WAP to demonstrate the use of signal – IPC (user defined Handler)

AIM: A program to demonstrate the use of signal - IPC


DESCRIPTION:
A signal is a software generated interrupt that is sent to a process by the OS because of when user press
ctrl-c or another process tell something to this process. There are fix set of signals that can be sent to a
process. signal are identified by integers. Signal number have symbolic names. For example SIGCHLD
is number of the signal sent to the parent process when child terminates.
CODE:
#include<stdio.h>
#include<signal.h>
// Handler for SIGINT, caused by
// Ctrl-C at keyboard
void handle_sigint(int sig) // Signal Handler
{
printf("Caught signal %d\n", sig);
}
int main()
{
signal(SIGINT, handle_sigint); // Registering a Signal
while (1)
{
printf(“hello world\n”);
sleep(1);
}
return 0;
}
OUTPUT:

91 | P a g e
5. WAP to demonstrate the SIGCHLD and SIGINT handling
AIM: A program to demonstrate the SIGCHLD and SIGINT handling
DESCRIPTION:
A signal is a software generated interrupt that is sent to a process by the OS because of when user press
ctrl-c or another process tell something to this process. There are fix set of signals that can be sent to a
process. signal are identified by integers. Signal number have symbolic names. For example SIGCHLD
is number of the signal sent to the parent process when child terminates.

CODE:
SIGINT handling:
#include<stdio.h>
#include<signal.h>
// Handler for SIGINT, caused by
// Ctrl-C at keyboard
void handle_sigint(int sig) // Signal Handler
{
printf("Caught signal %d\n", sig);
}
int main()
{
signal(SIGINT, handle_sigint); // Registering a Signal
while (1)
{
printf(“hello world\n”);
sleep(1);
}
return 0;
}
SIGCHLD handling:
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
// Handler for SIGINT, caused by
// Ctrl-C at keyboard
void handle_sigchild(int sig) // Signal Handler
{
printf("Inside child signal %d \n", sig);
//signal(SIGINT,SIG_DFL); //De registering Signal
}
int main()
{
signal(SIGCHLD, handle_sigchild); // Registering a Signal
int p=fork();
if(p==0)
{
printf("Inside Child process \n");
//
printf("End of child Process \n");
}
else if(p>=0)
92 | P a g e
{
printf("Inside parent process \n");
wait();

printf("End of parent process \n");


}
return 0;
}
OUTPUT:
SIGINT:

SIGCHLD:

6. WAP to demonstrate the use of shared memory – IPC


Ans.
93 | P a g e
AIM: A program to demonstrate the use of shared memory
DESCRIPTION:
Shared Memory is the fastest inter-process communication (IPC) method. The operating system maps

a memory segment in the address space of several processes so that those processes can read and write
in that memory segment. Two functions:shmget() and shmat() are used for IPC using shared memory.
shmget() function is used to create the shared memory segment while shmat() function is used to attach
the shared segment with the address space of the process.
CODE:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/shm.h>
#include<string.h>
int main()
{
int i;
void *shared_memory;

char buff[100];
int shmid;

shmid=shmget((key_t)2345, 1024, 0666|IPC_CREAT);

/*creates shared memory segment with key 2345, having size 1024 bytes. IPC_CREAT is used to create
the shared segment if it does not exist. 0666 are the permisions on the shared segment*/

printf("Key of shared memory is %d\n",shmid);


shared_memory=shmat(shmid,NULL,0); //process attached to shared memory segment
printf("Process attached at %p\n",shared_memory); //this prints the address where the segment is
attached with this process
printf("Enter some data to write to shared memory\n");
read(0,buff,100); //get some input from user
strcpy(shared_memory,buff); //data written to shared memory
printf("You wrote : %s\n",(char *)shared_memory);
}

OUTPUT:

7. WAP to demonstrate the use of semaphore – IPC


Ans.
AIM: A program to demonstrate the use of semaphore - IPC
DESCRIPTION:
Semaphore is an integer variable which is accessed or modified by using two atomic operations: wait()
and signal(). In C program the corresponding operations are sem_wait() and sem_post(). Here, we write

94 | P a g e
a Program for Process Synchronization using Semaphores to understand the implementation of
sem_wait() and sem_signal() to avoid a race condition.
CODE:

#include<pthread.h>
#include<stdio.h>

#include<semaphore.h>
#include<unistd.h>
void *fun1();
void *fun2();
int shared=1; //shared variable
sem_t s; //semaphore variable
int main()
{
sem_init(&s,0,1); //initialize semaphore variable - 1st argument is address of variable, 2nd is number of
processes sharing semaphore, 3rd argument is the initial value of semaphore variable
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, fun1, NULL);
pthread_create(&thread2, NULL, fun2, NULL);

pthread_join(thread1, NULL);
pthread_join(thread2,NULL);
printf("Final value of shared is %d\n",shared); //prints the last updated value of shared variable
}
void *fun1()

{
int x;
sem_wait(&s); //executes wait operation on s
x=shared;//thread1 reads value of shared variable
printf("Thread1 reads the value as %d\n",x);
x++; //thread1 increments its value
printf("Local updation by Thread1: %d\n",x);
sleep(1); //thread1 is preempted by thread 2
shared=x; //thread one updates the value of shared variable
printf("Value of shared variable updated by Thread1 is: %d\n",shared);
sem_post(&s);
}
void *fun2()
{
int y;
sem_wait(&s);
y=shared;//thread2 reads value of shared variable
printf("Thread2 reads the value as %d\n",y);
y--; //thread2 increments its value
printf("Local updation by Thread2: %d\n",y);
sleep(1); //thread2 is preempted by thread 1
shared=y; //thread2 updates the value of shared variable
printf("Value of shared variable updated by Thread2 is: %d\n",shared);
sem_post(&s);
}
OUTPUT:
95 | P a g e
8. WAP to demonstrate the use of Mutex – IPC
Ans.
AIM: A program to demonstrate the use of mutex - IPC
DESCRIPTION:
A situation where several processes access and manipulate the same data concurrently and the outcome
of the execution depends on the particular order in which the access takes place is called a race
condition. This Program uses threads to simulate race condition.
CODE:
#include<pthread.h>
#include<stdio.h>

#include<unistd.h>
void *fun1();
void *fun2();
int shared=1; //shared variable
int main()
{
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, fun1, NULL);

pthread_create(&thread2, NULL, fun2, NULL);


pthread_join(thread1, NULL);
pthread_join(thread2,NULL);
printf("Final value of shared is %d\n",shared); //prints the last updated value of shared variable
}
void *fun1()
{
int x;
x=shared;//thread one reads value of shared variable
printf("Thread1 reads the value of shared variable as %d\n",x);
x++; //thread one increments its value
printf("Local updation by Thread1: %d\n",x);
sleep(1); //thread one is preempted by thread 2
shared=x; //thread one updates the value of shared variable
printf("Value of shared variable updated by Thread1 is: %d\n",shared);
}
void *fun2()
{
int y;

96 | P a g e
y=shared;//thread two reads value of shared variable
printf("Thread2 reads the value as %d\n",y);
y--; //thread two increments its value

printf("Local updation by Thread2: %d\n",y);


sleep(1); //thread two is preempted by thread 1

shared=y; //thread one updates the value of shared variable


printf("Value of shared variable updated by Thread2 is: %d\n",shared);
}
OUTPUT:

9. WAP to demonstrate the use of message queue – IPC


Ans.
AIM: A program to demonstrate the use of message queue - IPC
DESCRIPTION:
Program for IPC using Message queues are almost similar to named pipes with the exception that they
do not require the opening and closing of pipes. But, they face one similar problem like named pipes;

blocking on full pipes. Message queues send blocks of data from one process to another. Each block of
data is considered to have a type. There is an upper limit on the maximum size of each block and also a
limit on the maximum total size of all blocks on all queues in the system.
CODE:
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>

#include<sys/msg.h>
#define MAX_TEXT 512 //maximum length of the message that can be sent allowed
struct my_msg{
long int msg_type;
char some_text[MAX_TEXT];
};
int main()
{
int running=1;
int msgid;
struct my_msg some_data;
char buffer[50]; //array to store user input
msgid=msgget((key_t)14534,0666|IPC_CREAT);

97 | P a g e
if (msgid == -1) // -1 means the message queue is not created
{
printf("Error in creating queue\n");

exit(0);
}

while(running)
{

printf("Enter some text:\n");


fgets(buffer,50,stdin);
some_data.msg_type=1;
strcpy(some_data.some_text,buffer);
if(msgsnd(msgid,(void *)&some_data, MAX_TEXT,0)==-1) // msgsnd returns -1 if the message is
not sent
{
printf("Msg not sent\n");
}
if(strncmp(buffer,"end",3)==0)
{
running=0;
}
}
}

OUTPUT:

10. WAP to demonstrate the use of socket – IPC

AIM: A program to demonstrate the use of socket - IPC


DESCRIPTION:
A socket is a bi-directional data transfer mechanism. They are used to transfer data between two
98 | P a g e
processes. The two processes can be running on the same system as Unix-domain or loopback sockets,

or on different systems as network sockets. Sockets allow communication between two different
processes on the same or different machines. To be more precise, it's a way to talk to other computers
using standard Unix file descriptors. In Unix, every I/O action is done by writing or reading a file
descriptor. A file descriptor is just an integer associated with an open file and it can be a network
connection, a text file, a terminal, or something else. A Unix Socket is used in a client-server application
framework. A server is a process that performs some functions on request from a client. Most of the
application-level protocols like FTP, SMTP, and POP3 make use of sockets to establish connection
between client and server and then for exchanging data.

CODE:
SOCKET:
#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#define MAX 80
#define PORT 8080
#define SA struct sockaddr

// Function designed for chat between client and server.


void func(int connfd)
{
char buff[MAX];
int n;
// infinite loop for chat

for (;;) {
bzero(buff, MAX);

// read the message from client and copy it in buffer


read(connfd, buff, sizeof(buff));
// print buffer which contains the client contents
printf("From client: %s\t To client : ", buff);
bzero(buff, MAX);
n = 0;
// copy server message in the buffer
while ((buff[n++] = getchar()) != '\n')
;

// and send that buffer to client


write(connfd, buff, sizeof(buff));

// if msg contains "Exit" then server exit and chat ended.


if (strncmp("exit", buff, 4) == 0) {
printf("Server Exit...\n");
break;
99 | P a g e
}
}
}

// Driver function
int main()

{
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;

// socket create and verification


sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));

// assign IP, PORT


servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);

// Binding newly created socket to given IP and verification


if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(0);
}
else

printf("Socket successfully binded..\n");

// Now server is ready to listen and verification


if ((listen(sockfd, 5)) != 0) {
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len = sizeof(cli);

// Accept the data packet from client and verification


connfd = accept(sockfd, (SA*)&cli, &len);
if (connfd < 0) {
printf("server accept failed...\n");
exit(0);
}
else
printf("server accept the client...\n");
100 | P a g e
// Function for chatting between client and server
func(connfd);

// After chatting close the socket


close(sockfd);
}
CLIENT:
#include <arpa/inet.h> // inet_addr()

#include <netdb.h>
#include <stdio.h>

#include <stdlib.h>
#include <string.h>
#include <strings.h> // bzero()
#include <sys/socket.h>
#include <unistd.h> // read(), write(), close()
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
void func(int sockfd)
{
char buff[MAX];
int n;
for (;;) {
bzero(buff, sizeof(buff));
printf("Enter the string : ");
n = 0;
while ((buff[n++] = getchar()) != '\n')
;
write(sockfd, buff, sizeof(buff));
bzero(buff, sizeof(buff));
read(sockfd, buff, sizeof(buff));
printf("From Server : %s", buff);

if ((strncmp(buff, "exit", 4)) == 0) {


printf("Client Exit...\n");
break;
}
}
}

int main()
{
int sockfd, connfd;
struct sockaddr_in servaddr, cli;

// socket create and verification


sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
101 | P a g e
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));

// assign IP, PORT


servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(PORT);

// connect the client socket to server socket


if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr))

!= 0) {
printf("connection with the server failed...\n");
exit(0);

}
else
printf("connected to the server..\n");

// function for chat


func(sockfd);

// close the socket


close(sockfd);
}
OUTPUT:

102 | P a g e

You might also like