0% found this document useful (0 votes)
5 views82 pages

OS Lab Manual

The document outlines the details of the Operating Systems Lab course at Stanley College of Engineering & Technology for Women, including course objectives, outcomes, and mapping with program outcomes and specific outcomes. It emphasizes the importance of Unix commands, process management, and memory management techniques in the curriculum. Additionally, it aligns course outcomes with Sustainable Development Goals (SDGs) to highlight the relevance of the skills taught in the lab to industry and societal needs.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views82 pages

OS Lab Manual

The document outlines the details of the Operating Systems Lab course at Stanley College of Engineering & Technology for Women, including course objectives, outcomes, and mapping with program outcomes and specific outcomes. It emphasizes the importance of Unix commands, process management, and memory management techniques in the curriculum. Additionally, it aligns course outcomes with Sustainable Development Goals (SDGs) to highlight the relevance of the skills taught in the lab to industry and societal needs.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

STANLEY COLLEGE OF ENGINEERING & TECHNOLOGY FOR WOMEN

(AUTONOMOUS)
(Affiliated to Osmania University, Approved by AICTE and Accredited
by NAAC)
Hyderabad - 500 001, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

OPERATING SYSTEMS LAB DETAILS

Course Code SPC0404CS Credits: 2 Evaluation: CIE - 40 Marks & SEE – 60 Marks

Name of the Student:

Roll Number:

Batch / Section: 2025 – 2026 / A, B and C

Duration of the Course:

Name of the Faculty: [Link] , [Link] , [Link] , [Link] Angeline, [Link]


STANLEY COLLEGE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Autonomous)
Abids, Hyderabad - 500 001, Telangana
Department of Computer Science and Engineering

Vision of the Institute


Empowering girl students through professional education integrated with values and character to
make an impact in the world.

Mission of the Institute


 Providing quality engineering education for girl students to make them
competent and confident to succeed in professional practice and advanced
learning.
 Establish state-of-art-facilities and resources to facilitate world class education.
 Integrating qualities like humanity, social values, ethics, leadership in order to encourage
contribution to society.

Vision of the Department


Empowering girl students with the contemporary knowledge in computer science engineering
for their success in life.

Mission of the Department


 To impart quality education for girl students to learn and practice various hardware and
software platforms prevalent in industry.
 To achieve self-sustainability and overall development through Research and
Development activities.
 To provide education for life by focusing on the inculcation of human & moral values
through an honest and scientific approach.
 To groom students with good attitude, team work and personality skills.

Program Educational Objectives (PEOs)

PEO1. Graduates shall have enhanced skills and contemporary knowledge in software and hardware
technologies for professional excellence, towards successful employment, advanced learning and
research.
PEO2. Graduates shall have life-long learning attitude, innovation and creativity to master latest
technologies, devise solutions for realistic and social issues in the society.
PEO3. Graduates shall have good attitude and personality skills, ethical values, teamwork and
leadership skill towards professionalism and ethical practices within the organization and the society
STANLEY COLLEGE OF ENGINEERING & TECHNOLOGY FOR WOMEN
Abids, Hyderabad - 500 001, Telangana

Department of Computer Science and Engineering

Program Outcomes (POs)


PO1. Engineering Knowledge: Apply knowledge of mathematics, natural science, computing, engineering fundamentals and
an engineering specialization as specified in WK1 to WK4 respectively to develop to the solution of complex engineering
problems.
PO2. Problem Analysis: Identify, formulate, review research literature and analyze complex engineering problems
reaching substantiated conclusions with consideration for sustainable development.
PO3. Design/Development of Solutions: Design creative solutions for complex engineering problems and design/develop
systems/components/processes to meet identified needs with consideration for the public health and safety, whole-life cost, net
zero carbon, culture, society and environment as required.

PO4. Conduct Investigations of Complex Problems: Conduct investigations of complex engineering


problems using research-based knowledge including design of experiments, modelling, analysis &
interpretation of data to provide valid conclusions.
PO5. Engineering Tool Usage: Create, select and apply appropriate techniques, resources and modern engineering & IT
tools, including prediction and modelling recognizing their limitations to solve complex engineering problems.
PO6. The Engineer and The World: Analyze and evaluate societal and environmental aspects while solving complex engineering
problems for its impact on sustainability with reference to economy, health, safety, legal framework, culture and environment.

PO7. Ethics: Apply ethical principles and commit to professional ethics, human values, diversity and inclusion;
adhere to national & international laws.
PO8. Individual and Collaborative Team work: Function effectively as an individual, and as a member or leader in
diverse/multi-disciplinary teams.
PO9. Communication: Communicate effectively and inclusively within the engineering community and society at large, such as
being able to comprehend and write effective reports and design documentation, make effective presentations considering
cultural, language, and learning differences.

PO10. Project Management and Finance: Apply knowledge and understanding of engineering management
principles and economic decision-making and apply these to one’s own work, as a member and leader in a team,
and to manage projects and in multidisciplinary environments.
PO11. Life-Long Learning: Recognize the need for, and have the preparation and ability for i) independent and life- long
learning ii) adaptability to new and emerging technologies and iii) critical thinking in the broadest context of
technological change.

Program Specific Outcomes (PSOs)


PSO1. Problem-Solving Skills: The ability to apply standard practices and strategies in software project development using open-
ended programming environments to deliver a quality product for the benefit of students.
PSO2. Design, Implement, Test and Evaluate a computer system, component or algorithm to meet desired needs and to solve a
computational problem.
STANLEY COLLEGE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Autonomous)
Abids, Hyderabad - 500 001, Telangana

Department of Computer Science and Engineering

Objectives and Outcomes of Operating Systems Lab (SPC0404CS)

Course Objectives:
 Understand Unix commands.
 Implement process management related techniques.
 Implement memory management techniques.

Course Outcomes:
After completing this course, the student will be able to:
 Execute the Unix commands.
 Implement CPU scheduling algorithms.
 Implement producer–consumer problem, reader–writers problem, dining philosophers’ problem.
 Apply Banker’s algorithm for deadlock avoidance.
 Implement page replacement and disk scheduling techniques.
STANLEY COLLEGE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Autonomous)
Abids, Hyderabad - 500 001, Telangana
Department of Computer Science and Engineering
Mapping of Operating Systems Lab Course Outcomes with POs and PSOs
Program
Course Outcomes Specific
Program Outcomes (POs)
(COs) Outcomes
(PSOs)
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PSO1 PSO2
1. Execute the Unix
commands. 1 3 3 2 1 1 1 1 1 3 3

[Link] CPU
scheduling algorithms. 2 3 3 2 1 1 1 1 1 3 3

3 Implement producer–
consumer problem, 2 3 3 2 1 1 1 1 1 3 3
reader–writers
problem, dining
philosophers’ problem.

4. Apply Banker’s
algorithm for deadlock 2 3 3 2 1 1 1 1 1 3 3
avoidance

5. Implement page
replacement and 2 3 3 2 1 1 1 1 1 3 3
disk scheduling
techniques
STANLEY COLLEGE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Autonomous)
Abids, Hyderabad - 500 001, Telangana
Department of Computer Science and Engineering
Mapping of Operating Systems Lab with SDGs

Roll No:
Name:
Class, Semester & Section: B.E, VII & A, B and C
Academic Year: 2025-2026

Name of the Faculty: [Link] , [Link] , [Link] , [Link] Angeline, [Link]

Course Outcomes (COs) Mapping with SDGs:


Course Outcomes
(COs) Relevant SDGs Justification of SDGs

1. Execute the Unix  SDG 4 – Quality Learning and executing Unix commands builds
commands. Education strong foundational computing and problem-
solving skills, directly supporting quality technical
education (SDG 4). Unix systems are widely used in
 SDG 9 – Industry,
servers, cloud platforms, and research
Innovation and infrastructure; thus, this outcome contributes to
Infrastructure robust digital infrastructure and innovation (SDG 9).

2. Implement CPU  SDG 9 – Industry, CPU scheduling improves efficient utilization of


scheduling algorithms. Innovation and processing resources, which is essential for
Infrastructure reliable and scalable computing systems (SDG
9). Efficient scheduling reduces wasted CPU
 SDG 12 – Responsible cycles and energy consumption, promoting
Consumption and responsible and sustainable use of computational
Production resources (SDG 12).

3 Implement producer–  SDG 9 – Industry, These classic synchronization problems teach


consumer problem, reader– Innovation and concurrency control and coordination in multi-
writers problem, dining Infrastructure process systems, which are critical for building
philosophers’ problem. reliable software infrastructure (SDG 9). Mastery
of such concepts prepares students for industry-
 SDG 8 – Decent Work ready software development roles, supporting
and Economic Growth productive employment and economic growth (SDG
8).

4. Apply Banker’s algorithm  SDG 9 – Industry, Deadlock avoidance ensures system reliability and
for deadlock avoidance Innovation and continuous availability of computing resources,
Infrastructure strengthening resilient infrastructure (SDG 9).
Banker’s algorithm promotes optimal allocation
and prevents resource wastage, aligning with
 SDG 12 – Responsible responsible resource management (SDG 12).
Consumption and
Production
5. Implement page  SDG 9 – Industry, Memory and disk management techniques
replacement and disk Innovation and enhance system performance and scalability,
scheduling techniques Infrastructure which are vital for modern digital infrastructure
(SDG 9). Efficient page replacement and disk
 SDG 12 – Responsible scheduling reduce unnecessary I/O operations,
Consumption and leading to lower energy consumption (SDG 7) and
Production sustainable use of hardware resources (SDG 12).

 SDG 7 – Affordable and


Clean Energy
STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

STANLEY COLLEGE OF ENGINEERING & TECHNOLOGY FOR


WOMEN
(Autonomous)
Abids, Hyderabad - 500 001, Telangana
Department of Computer Science and Engineering

Mapping of Operating Systems Lab Programs with POs, PSOs and SDGs

SNO PROGRAM NAME POS PSOS SDGS


1. Write a C programs to implement UNIX system calls and file management 1,3,5,8,11 1,2 4,9

2. Write C programs to demonstrate various process related concepts. 1,2,5,8 1,2 9,8

3. Write C programs to demonstrate various thread related concepts. 1,3,5,8,9, 1,2 9,12
11

4. Write C programs to simulate CPU scheduling algorithms: FCFS, SJF, Round 1,3,5,8,9 1,2 9,12
Robin

5. Write C programs to simulate Intra & Inter-Process 1,2,4,5,11 1,2 9,8


Communication (IPC) techniques: Pipes, Messages, Queues, Shared Memory.

6. Write C programs to simulate solutions to Classical 1, 5, 8 1,2 9,12


Process Synchronization Problems:
Dining Philosophers, Producer-Consumer, Readers- Writers
7. Write a C program to simulate Bankers Algorithm 1,3,5,6,8, 1,2 9,12
for Deadlock Avoidance. 11
8. Write C programs to simulate Page Replacement Algorithms: FIFO, LRU 1,2,3,4,5, 1,2 7,9,12
8,11

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

EXPERIMENT 1 :Write a C programs to implement UNIX system calls and file management

1.A) Printing file flags for specified Descriptor.

AIM : To write the program to printing file flags for specified descriptor.

PROGRAM DESCRIPTION:

File systems have methods to assign permissions or access rights to specific


users and groups of users. These systems control the ability of the users to view, change,
navigate, and execute the contents of the file system.
Attributes of a File
Name – only information kept in human-readable form
• Identifier – unique tag (number) identifies file within file system
• Type – needed for systems that support different types
• Location – pointer to file location on device
• Size – current file size
• Protection – controls who can do reading, writing, executing
• Time, date, and user identification – data for protection, security, and usage
monitoring
#include<unistd.h>- In the C and C++ programming languages, unistd.h is the name of
the header file that provides access to the POSIX operating system API.

#include<fcntl.h>- In Unix-like systems, the interface defined by unistd.h is typically made up


largely of system call wrapper functions such as fork, pipe and I/O primitives (read,
write, close, etc.).

h is the header in the C POSIX library for the C programming language that contains constructs
that refer to file control, e.g. opening a file, retrieving and changing the permissions of file,
locking a file for edit, etc.

The sys/types.h header file defines a collection of typedef symbols and structures.

The stat data structure in the /usr/include/sys/stat.h file returns information for
the stat, fstat, lstat, statx, and fstatx subroutines.

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

PROGRAM CODING :

#include<unistd.h>

#include<fcntl.h>

#include<stdio.h>

#include<sys/types.h>

#include<sys/stat.h>

int main(int argc,char *argv[]) /*command line argument . argc counts the number
of arguments. It counts the file name as the first argument.
The argv[] contains the total number of arguments. The first argument is the
file name always. */

if(argc != 2)

printf(“wrong number of arguments”);

exit(1);

else

{ Struct stat str;

Stat(argv[1],&str);

printf(“\n mode is %lu \n”,str.st_mode); // %lu is long datatype

printf(“device type is %lu \n”,str.st_dev);

printf(“mode no. is %lu \n”,str.st_ino);

printf(“[Link] links is %lu \n”,str.st_nlink);

printf(“user id is %lu \n”,str.st_uid);

printf(“group id is %lu \n”,str.st_gid);

printf(“device name is %lu \n”,str.st_rdev);

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

printf(“block size is %lu \n”,str.st_blksize);

printf(“no. of blocks is %lu \n”,str.st_blocks);

} return (0);

OUTPUT:

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

EXPERIMENT 1.B : Recursively descend a directory hierarchy counting file types

AIM: To write the program to print recursively descend a directory hierarchy counting file
types.

PROGRAM CODING

#include<stdio.h>
#include<dirent.h> //dirent.h - format of directory entries
#include<errno.h>

/*The <errno.h> header file defines the integer variable errno,which is set by system
calls and some library functions in the event of an error to indicate what went wrong.
*/
#include<fcntl.h>
main(int argc,char *argv[])
{
struct dirent *direntp;
DIR *dirp;
if(argc != 2)
{
printf("Usage: %s directory name\n",argv[0]);
return 1;
}
if((dirp=opendir(argv[1]))==NULL)
{
perror("Failed to open directry\n");
return 1;
}
while((direntp=readdir(dirp))!= NULL)
printf("%s\n",direntp->d_name);
while((closedir(dirp)==-1) && (errno==EINTR));
return 0;
}
OUTPUT:
[swapna@linuxstuserver ses4]$ cc 5dirfiltyp.c
[swapna@linuxstuserver ses4]$ ./[Link] dir
[Link]
1
3
..
2 [Link]

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

EXPERIMENT: 2 Program using Process related system calls.

AIM: To write the program using Process system calls.

2.1) Fork()
2.2) Factorial of a number using fork()
2.3) Process Heirarchy
2.4) wait()
2.5) exec()
2.6) sleep()

PROGRAM DESCRIPTOR:

SYSTEM CALLS USED :

1. fork( ) Used to create new processes. The new process consists of a copy of the
address space of the original process. The value of process id for the child process is
zero, whereas the value of process id for the parent is an integer value greater than
zero.

Syntax : fork( )

2. execlp( ) Used after the fork() system call by one of the two processes to replace the
process‟ memory space with a new program. It loads a binary file into memory
destroying the memory image of the program containing the execlp system call and
starts its [Link] child process overlays its address space with the UNIX
command /bin/ls using the execlp system call.

Syntax : execlp( )

3. wait( ) The parent waits for the child process to complete using the wait system
call. The wait system call returns the process identifier of a terminated child, so that
the parent can tell which of its possibly many children has terminated.
Syntax : wait( NULL)

4. exit( ) A process terminates when it finishes executing its final statement and asks
the operating system to delete it by using the exit system call. At that point, the
process may return data (output) to its parent process (via the wait system call).

Syntax: exit(0)

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

ALGORITHM :

Step 1 : Declare the variable pid.


Step 2 : Get the pid value using system call fork().
Step 3 : If pid value is less than zero then print as “Fork failed”.
Step 4 : Else if pid value is equal to zero include the new process in the systems file
using execlp system call.
Step 5 : Else if pid is greater than zero then it is the parent process and it waits till the
child completes using the system call wait() .
Step 6 : Then print “Child complete”.

PROGRAM CODING:

2.1) FORK() system call

#include<stdio.h>

#include<sys/types.h>

main()

int id,childid;

id=getpid();

if(childid = fork()>0)

printf("\n i am in the parent process %d",id);

printf("\n i am in the parent process %d",getpid());

printf("\n i am in the parent process %d\n",getppid());

else

printf("\n i am in child process %d",id);

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

printf("\n i am in the child process %d",getpid());

printf("\n i am in the child process %d",getppid());

OUTPUT:

"1forksyscal.c" [New] 22L, 420C written

[swapna@linuxstuserver ses5]$ cc 1forksyscal.c

[swapna@linuxstuserver ses5]$ ./[Link]

i am in child process 1231

i am in the child process 1232

i am in the child process 1231

i am in the parent process 1231

i am in the parent process 1231

i am in the parent process 962

2.2) Factorial of a number using fork()

#include<stdio.h>

#include<sys/types.h>

void main()

int pid,f=1,n;

printf("enter a number\n");

scanf("%d",&n);

pid=fork();

printf("\nmy pid now is %d",pid);

if(pid==0)

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

printf("\n i am in child process");

while(n>0)

f=f*n;

n--;

printf("\nfactorial of a number%d",f);

else {

printf(" \nnow i am in the parent process");

printf("\n factorial of a number is %d",f);

OUTPUT:

[sireesha@localhost lab2]$ ./[Link]

enter a number

my pid now is 0

i am in child process

factorial of a number120

my pid now is 10757

now i am in the parent process

factorial of a number is 1[sireesha@localhost lab2]

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

[Link] a program to implement process hierarchy

#include<stdio.h>

#include<sys/types.h>

main()

int pid,pid1,pid2,pid3,pid4;

pid=fork();

if(pid==0)

printf("i am A%d\n",getpid());

printf("i am parentA%d\n",getppid());

pid1=fork();

if(pid1==0)

printf(" i am B%d\n",getpid());

printf(" parent of B%d\n",getppid());

pid3=fork();

if(pid3==0)

printf("i am c %d\n",getpid());

printf("parent of c %d\n",getppid());

else

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

pid2=fork();

if(pid2==0)

printf("i am D%d\n",getpid());

printf(" parent of D%d\n",getppid());

pid4=fork();

if(pid4==0)

printf(" iam E%d\n",getpid());

printf(" parent of E %d\n",getppid());

}}

OUTPUT:

[sireesha@server tree]$ cc fktree.c

[sireesha@server tree]$ ./[Link]

i am A5184

i am parentA5183

i am B5185

parent of B5184

i am c 5186

parent of c 5185

i am D5187

parent of D1

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

iam E5188

parent of E 5187

[Link]() system call

#include<stdio.h>

#include<sys/types.h>

void main()

int i=0,pid;

pid=fork();

if(pid==0)

printf("child process \n");

for(i=0;i<5;i++)

printf("\n%d",i);

else

{ printf("parent process\n");

for(i=10;i<15;i++)

wait();

printf("process ends\n");

OUTPUT:

[sireesha@localhost lab2]$ ./[Link]

child process

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

parent process

process ends

[Link]()

#include<stdio.h>

#include<sys/types.h>

main(int argc,char *argv[])

printf("before execv\n");

execv("/bin/date",argv);

printf("after execv\n");

OUTPUT:

[sireesha@localhost lab2]$ ./[Link]

before execv

Mon Jan 24 14:55:27 IST 2011

[Link]() system call

#include<stdio.h>

#include<sys/types.h>

#include<unistd.h>

void main()

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

int pid,i;

pid=fork();

switch(pid)

case 0: printf("child process\n");

sleep(4);

for(i=0;i<5;i++)

printf("\n%d",i);

break;

case -1:printf("error");

break;

default:

printf("i am parent process\n");

for(i=6;i<10;i++)

printf("\n%d",i);

break;

OUTPUT:

[sireesha@localhost lab2]$ ./[Link]

child process

i am parent process

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

9[sireesha@localhost lab2]$

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

EXPERIMENT 3 : Programs to create threads.

AIM: To write the program using threads.

PROGRAM DESCRIPTION

Thread is an execution unit which consists of its own program counter, a stack, and a set of
registers. Threads are also known as Lightweight processes. Threads are popular way to
improve application through parallelism. The CPU switches rapidly back and forth among the
threads giving illusion that the threads are running in parallel.

Types of Thread
There are two types of threads :

 User Threads
 Kernel Threads

User threads, are above the kernel and without kernel support. These are the threads
that application programmers use in their programs.
Kernel threads are supported within the kernel of the OS itself. All modern OSs
support kernel level threads, allowing the kernel to perform multiple simultaneous
tasks and/or to service multiple kernel system calls simultaneously.
When multiple threads are running they will invariably need to communicate with each other
inorder synchronize their execution. One main benefit of using threads is the ease of using
synchronization facilities

pthread_self(): This function returns the ID of the callingthread.

#include <pthread.h>
pthread_t pthread_self(void);

pthread_exit():This function terminates the calling thread andmakesthe


value value_ptr available toany successful join with the terminatingthread.

#include <pthread.h>
void pthread_exit(void *value_ptr);
pthread_create() : This function creates a new thread of control that executes concurrently
withthe calling thread. The new thread applies the function start_routine passing it arg as
firstargument. The new thread terminates either explicitly, by calling pthread_exit(), or
implicitly, byreturning from the start_routine function. The latter case is equivalent to calling
pthread_exit()with the result returned by start_routine as exit [Link] attr argument
specifies thread attributesto be applied to the new thread.

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

#include <pthread.h>
int pthread_create(pthread_t * thread, pthread_attr_t * attr, void *(*start_routine)(void *),
void * arg);

pthread_join()
pthread_join suspends the execution of the calling thread until the thread identified by
th terminates, either by calling pthread_exit() or by being cancelled. If thread_return is not
NULL, the return value of th is stored in the location pointed to by thread_return. The return
value of th is either the argument it gave to pthread_exit(), or PTHREAD_CANCELED if
th was [Link] joined thread th must be in the joinable state.

#include <pthread.h>
int pthread_join(pthread_t th, void **thread_return);

ALGORITHM :

1: Create a thread and prints its id


2:Assign a task to a thread (sum of first 10 numbers)
3: Wait for thread to terminate and then print the sum
3.1 -Multithreaded C program using Pthread API

PROGRAM CODE:

#include<stdio.h>

#include<pthread.h>

#include<sys/types.h>

#include<unistd.h>

int s;

void *runner(void *param);

int main(int argc,char *argv[])

pthread_attr_t attr;

pthread_t tid;

if(argc!=2)

printf(stderr,"usage:[Link]<integervalues>\n");

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

return -1;

pthread_attr_init(&attr);

pthread_create(&tid,&attr,runner,argv[1]);

pthread_join(tid,0);

printf("sum=%d",s);

void *runner(void *param)

int i,upper;

upper=atoi(param);

s=0;

for(i=0;i<=upper;i++)

s+=i;

pthread_exit(0);

OUTPUT

[swapna@server ~]$ cc thread.c -pthread

thread.c: In function âmainâ:

thread.c:13: warning: passing argument 1 of âprintfâ from incompatible pointer type

[swapna@server ~]$ ./[Link] 10

sum=55[sireesha@server ~]$

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

3.2- cancellation of thread

PROGRAM CODE:

#include<stdio.h>

#include<unistd.h>

#include<pthread.h>

void* th(void*);

int main()

pthread_t t1;

int c;

void* r;

c=pthread_create(&t1,NULL,th,NULL);

if(c!=0)

printf("not created\n");

exit(0);

sleep(3);

printf("canceling thread\n");

c=pthread_cancel(t1);// canceling thread t1

if(c!=0)

printf("main cant send signal\n");

exit(0);

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

c=pthread_join(t1,&r);

if(c!=0)

printf("cant be joined\n");

exit(0);

printf("main exiting and th has executed ");

return 0;

void* th(void* p)

int i,r;

r=pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);//setting cancel state to


be enabled

if(r!=0)

printf("we cant can ena\n");

exit(0);

r=pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL);//setting type of
cancellation to be deferred

for(i=0;i<10;i++)

sleep(1);

printf("thread run %d",i);

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

pthread_exit(NULL);//returning nothing to main

OUTPUT:

[sireesha@localhost lab4]$ ./[Link]

thread run 0thread run 1canceling thread

main exiting and thread has executed

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

3.3-Counting number of thread

PROGRAM CODE:

#include <unistd.h>

#include<stdio.h>

#include<pthread.h>

void* th(void*);

int main()

pthread_t t1,t2;

int c;

void* r;

pthread_create(&t1,NULL,th,NULL);

pthread_create(&t2,NULL,th,NULL);

pthread_join(t1,&r);

pthread_join(t2,&r);

int i=0 ;//using a global variable to count no of threads;

void* th(void* p)

{++i;

printf("Now threads are:%d",i);//every time printing the count

pthread_exit(NULL);}

OUTPUT:

[swapna@localhost lab4]$ cc thrcount.c -pthread

[swapna@localhost lab4]$ ./[Link]

Now threads are:1Now threads are:2

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

EXPERIMENT 4 : Implement CPU scheduling algorithms (A) Round Robin (B) SJF (c)
FCFS

AIM: A) To write the program to simulate the Round Robin program..

PROGRAM DESCRIPTION:

CPU scheduler will decide which process should be given the CPU for its execution. For
this it use different algorithm to choose among the process. One among that algorithm is
Round robin algorithm. In this algorithm we are assigning some time slice .The process is
allocated according to the time slice, if the process service time is less than the time slice
then process itself will release the CPU voluntarily. The scheduler will then proceed to the
next process in the ready queue .If the CPU burst of the currently running process is longer
than time quantum, the timer will go off and will cause an interrupt to the operating system.
A context switch will be executed and the process will be put at the tail of the ready queue.

ALGORITHM:

Step 1: Initialize all the structure elements


Step 2: Receive inputs from the user to fill process id,burst time and arrival time.
Step 3: Calculate the waiting time for all the process id.
i) The waiting time for first instance of a process is calculated as:
a[i].waittime=count + a[i].arrivt
ii) The waiting time for the rest of the instances of the process is calculated
as:
a) If the time quantum is greater than the remaining burst time then
waiting time is calculated as:
a[i].waittime=count + tq
b) Else if the time quantum is greater than the remaining burst time then
waiting time is calculated as:
a[i].waittime=count - remaining burst time
Step 4: Calculate the average waiting time and average turnaround time
Step 5: Print the results of the step 4.

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

PROGRAM CODE:

#include<stdio.h>

#include<stdio.h>

void main()

Int i,tbt=0,nop,ts=0,flag[20], rem[20];

intfrom,wt[20],tt[20],b[20], twt=0,ttt=0;

int dur;

float awt,att;

printf("Enter no. of Processes: ");

scanf("%d",&nop);

printf("Enter the time slice: ");

scanf("%d",&ts);

printf("Enter the Burst times..\n");

for(i=0;i<nop;i++)

wt[i]=tt[i]=0;

printf("P%d\t: ",i+1);

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

rem[i]=b[i];

tbt+=b[i];

flag[i]=0;

from=0;

i=0;

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

printf("\n\t Gantt Chart");

printf("\n ProcessID\tFrom Time\tTo Time\n");

while(from<tbt)

if(!flag[i])

if(rem[i]<=ts)

dur=rem[i];

flag[i]=1;

tt[i]=dur+from;

wt[i]=tt[i]-b[i];

else

dur=ts;

printf("%7d%15d%15d\n",i+1, from,from+dur);

rem[i] -= dur;

from += dur;

i=(i+1)%nop;

for(i=0;i<nop;i++)

twt+=wt[i];

ttt+=tt[i];

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

printf("\n\n Process ID \t Waiting Time \t Turn AroundTime");

for(i=0;i<nop;i++)

printf("\n\t%d\t\t%d\t\t%d",i+1,wt[i],tt[i]);

awt=(float)twt/(float)nop;

att=(float)ttt/(float)nop;

printf("\nTotal Waiting Time:%d",twt);

printf("\nTotal Turn Around Time:%d",ttt);

printf("\nAverage Waiting Time:%.2f",awt);

printf("\nAverage Turn Around Time:%.2f\n",att);

AIM: B) To write a C program to implement the CPU scheduling algorithm for shortest job
first.

PROGRAM DESCRIPTION

Cpu scheduler will decide which process should be given the CPU for its execution. For this
it uses different algorithm to choose among the process. One among that algorithm is SJF
algorithm. In this algorithm the process which has less service time given the cpu after
finishing its request only it will allow cpu to execute next other process.

ALGORITHM:

Step 1: Get the number of process.


Step 2: Get the id and service time for each process.
Step 3: Initially the waiting time of first short process as 0 and total time of first short is
process the service time of that process.
Step 4: Calculate the total time and waiting time of remaining process.

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

Step 5: Waiting time of one process is the total time of the previous process.
Step 6: Total time of process is calculated by adding the waiting time and service time of
each process.
Step 7: Total waiting time calculated by adding the waiting time of each process.
Step 8: Total turn around time calculated by adding all total time of each process.
Step 9: Calculate average waiting time by dividing the total waiting time by total number of
process. Step 10: Calculate average turn around time by dividing the total waiting time by
total number of process.
Step 11: Display the result.

PROGRAM CODING:

#include<stdio.h>

int main()

int n,w[100],tot[100],i,j,awt,atot;

float avwt,avtot;

struct

int p,bt;

sjf[10],temp;

printf("Enter the number of Processes:");

scanf("%d",&n);

for(i=1;i<=n;i++)

printf("Enter the Burst time for Process%d : ",i);

scanf("%d",&sjf[i].bt);

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

sjf[i].p=i;

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

if(sjf[j].bt>sjf[i].bt)

temp=sjf[i];

sjf[i]=sjf[j];

sjf[j]=temp;

w[1]=0;

tot[1]=sjf[1].bt;

for(i=2;i<=n;i++)

tot[i]=tot[i-1]+sjf[i].bt;

awt=0;

atot=0;

for(i=1;i<=n;i++)

w[i]=tot[i]-sjf[i].bt;

awt+=w[i];

atot+=tot[i];

avwt=(float)awt/n;

avtot=(float)atot/n;

printf("\n\nProcessId\tWaiting time\t TurnaroundTime");

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

for(i=1;i<=n;i++)

printf("\n\t%d\t\t%d\t\t%d",sjf[i].p,w[i],tot[i]);

printf("\n\nTotal Waiting Time :%d",awt);

printf("\n\nTotal Turnaround Time :%d",atot);

printf("\n\nAverage Waiting Time :%.2f",avwt);

printf("\n\nAverage Turnaround Time :%.2f",avtot);

AIM: C ) To write a C program to implement the CPU scheduling algorithm for first come
first serve.

PROGRAM DESCRIPTION:

Cpu scheduler will decide which process should be given the CPU for its [Link] this it
uses different algorithm to choose among the process. One among that algorithm is FCFS
algorithm. In this algorithm the process which arrive first is given the cpu after finishing its
request only it will allow cpu to execute other process.

ALGORITHM:

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

Step 1: Create the number of process.


Step 2: Get the ID and Service time for each process.
Step 3: Initially, Waiting time of first process is zero and Total time for the first process is the
starting time of that process.
Step 4: Calculate the Total time and Processing time for the remaining processes.
Step 5: Waiting time of one process is the Total time of the previous process.
Step 6: Total time of process is calculated by adding Waiting time and Service time.
Step 7: Total waiting time is calculated by adding the waiting time for lack process.
Step 8: Total turn around time is calculated by adding all total time of each process.
Step 9: Calculate Average waiting time by dividing the total waiting time by total number of
process.
Step 10: Calculate Average turn around time by dividing the total time by the number of
process. Step 11: Display the result.

PROGRAM CODING:

#include<stdio.h>
int main()
{
int n,b[10],t=0,i,w=0,r=0,a=0;

float avg,avg1;
printf("\nEnter number of processes:");
scanf("%d",&n); printf("\nEnter the burst times : \n");
for(i=1;i<=n;i++)
scanf("%d",&b[i]);
printf("\n Gantt chart ");
for(i=1;i<=n;i++)
printf("P%d\t",i);
printf("\n\nProcess BurstTime WaitingTime TurnaroundTime\n");
for(i=1;i<=n;i++)
{
t=t+w;
r=r+b[i];

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

printf("P%d\t\t%d\t\t%d\t\t%d\t\t\n",i,b[i],w,r);
w=w+b[i];
a=a+r;
}
avg=(float)t/n;
avg1=(float)a/n;
printf("\n Average WaitingTime is %f",avg);
printf("\n Average TurnaroundTime is %f\n",avg1);
return(0);
}

OUTPUT:
[cse6@localhost Pgm]$ cc prog9a.c -o [Link]
[cse6@localhost Pgm]$ ./[Link]
Enter number of processes : 3
Enter the burst times :
24
5
3

Gantt chart P1 P2 P3

Process BurstTime WaitingTime Turnarou


ndTime
P1 24 0 24
P2 5 24 29
P3 3 29 32

Average WaitingTime is 17.666666


Average TurnaroundTime is 28.333334

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

EXPERIMENT 5 :Write C programs to simulate Intra & Inter-Process


Communication (IPC) techniques: Pipes, MessagesQueues.

5 .A Echo server using pipes


AIM: To write a program to implement Echo server using pipes.
PROGRAM DESCRIPTION :

A client process sends a request message to a server process. The server process sends a
response to the request back to the client. The client echoes the server response at it side. This
type of communication is called echoserver and it is used for trouble shooting.

The client server processes share a hierarchical relationship [Link] child. The parent process
is the server and the child process is created using the fork() it could be vice versa

fork() to create a child process. One (the parent process) reads write to the pipe and child
process
reads the data from the pipe ans then prints the data to the screen.

Pipe provide unidirectional from of communication 2 pipes are used 1 process reads from 1
pipe and wirtes to 2nd

P[0],p1[0]// read descriptor

P[1],p1[1]//write descriptor

in order to communicate the client and server using message queue to read and write
msgsnd() and mgsrcv() calls are used respectively

ALGORITHM :

1. Create two pipes pipe1 and pipe2


2. Create a child process
3. Child closes read end of pipe1
4. Child closes write end of pipe2
5. Child writes to pipe1 and waits for response from parent
6. Parent closes write end of pipe1
7. Parent closes read end of pipe2
8. Parent reads data from pipe1 and writes to pipe2 for child to read
9. Child reads data written by parent to pipe2 through read end of pipe2 and displays on
console.

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

PROGRAM CODE :

#include <sys/types.h>

#include <sys/ipc.h>

#include <stdio.h>

#include <string.h>

#define MAX 60

main()

int a, b, fdclient[2], fdserver[2], pid;

char client[MAX], server[MAX], buff1[MAX], buff2[MAX];

a = pipe(fdclient);

b = pipe(fdserver);

if( a == 0 && b == 0)

{ pid = fork();

if (pid > 0)

close(fdserver[0]);

close(fdclient[1]);

read(fdclient[0], buff1, MAX);

printf("Server Process\n");

printf("Enter server message: \t");

scanf("%s", server);

write(fdserver[1], server, MAX);

printf("Server message sent \n");

sleep(2);

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

printf("\n Client message at server is: %s\n", buff1);

else if (pid == 0)

printf("Client Prcoess\n");

printf("Enter client message: \t");

scanf("%s", client);

close(fdclient[0]);

close(fdserver[1]);

write(fdclient[1], client, MAX);

printf("Client message sent\n");

sleep(2);

read(fdserver[0], buff2, MAX);

printf("\n Server message at client is: %s\n", buff2);

else

printf("Error\n");

OUTPUT:

[swapna@linuxserver ~]$ cc pipe1.c

[swapna@linuxserver ~]$ ./[Link]

hello world swap

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

EXPERIMENT : 5.B Echo server using messages

AIM: To write a program to implement Echo server using messages.

PROGRAM CODE :

#include <sys/types.h>

#include <sys/ipc.h>

#include <stdio.h>

#include <string.h>

#define MAX 60

main()

int a, b, fdclient[2], fdserver[2], pid;

char client[MAX], server[MAX], buff1[MAX], buff2[MAX];

a = pipe(fdclient);

b = pipe(fdserver);

if( a == 0 && b == 0)

pid = fork();

if (pid > 0)

close(fdserver[0]);

close(fdclient[1]);

read(fdclient[0], buff1, MAX);

printf("Server Process\n");

printf("Enter server message: \t");

scanf("%s", server);

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

write(fdserver[1], server, MAX);

printf("Server message sent \n");

sleep(2);

printf("\n Client message at server is: %s\n", buff1);

else if (pid == 0)

else

printf("Client Prcoess\n");

printf("Enter client message: \t");

scanf("%s", client);

close(fdclient[0]);

close(fdserver[1]);

write(fdclient[1], client, MAX);

printf("Client message sent\n");

sleep(2);

read(fdserver[0], buff2, MAX);

printf("\n Server message at client is: %s\n", buff2);

printf("Error\n");

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

OUTPUT:

[swapna@linuxserver ~]$ cc pipe1.c

[swapna@linuxserver ~]$ ./[Link]

Client process

Enter client message:Hi how r u

Client msg send

Server Process

Enter server message:Fine what about u

Server message at Client : Fine What about u

Server message sent.

Client Message at server is: Hi how r u

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

EXPERIMENT 6 :.Producer- Consumer problem using shared memory.

AIM: To write a program to implement Producer –Consumer problem using shared


memory.

PROGRAM DESCRIPTION:

Shared Memory - is an efficeint means of passing data between programs. One program will
create a memory portion which other processes (if permitted) can access.A process creates a
shared memory segment using shmget(),The original owner of a shared memory segment can
assign ownership to another user with shmctl(). It can also revoke this assignment. Other
processes with proper permission can perform various control functions on the shared
memory
segment using shmctl(). Once created, a shared segment can be attached to a process
addressspace using shmat(). It can be detached using shmdt() The attaching process must have
theappropriate permissions for shmat(). Once attached, the process can read or write to the
segment, as allowed by the permission requested in the attach operation. A shared segment can
be attachedmultiple times by the same process. A shared memory segment is described by a
controlstructure with a unique ID that points to an area of physical memory. The identifier of
thesegment is called the shmid. The structure definition for the shared memory segment
controlstructures and prototype can be found in <sys/shm.h>

One shmid data structure for each shared memory segment in the system. */

struct shmid_ds {
struct ipc_perm shm_perm; /* operation perms */
int shm_segsz; /* size of segment (bytes) */
time_t shm_atime; /* last attach time */
time_t shm_dtime; /* last detach time */
time_t shm_ctime; /* last change time */
unsigned short shm_cpid; /* pid of creator */
unsigned short shm_lpid; /* pid of last operator */
short shm_nattch; /* no. of current attaches */
`}
shmget () - allocates a System V shared memory
segment Syntax:
#include <sys/ipc.h>
#include <sys/shm.h>
int shmget(key_t key, size_t size, int shmflg);

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

PROGRAME CODE :
#include<stdio.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/sem.h>
#include<sys/ipc.h>
static int pid,semid,shmid,cntid;
char *ptr,*ctr;
struct sembuf sop;
main()
{
int i;
semid=semget((key_t)10,1,IPC_CREAT|0666);
shmid=shmget((key_t)11,100,IPC_CREAT|0666);
cntid=shmget((key_t)12,2,IPC_CREAT|0666);
semctl(semid,0,SETVAL,1);
ptr=(char*)shmat(shmid,0,0);
ctr=(char*)shmat(cntid,0,0);
ctr[i];
pid=fork();
if(pid==0)
{
printf("producer starts \n");
producer();

printf("\n producer ends \n");


}
else
{
printf("\n consumer starts");
consumer();
printf("\n consumer ends");
}
}
code1()
{
sop.sem_num=0;
sop.sem_op=-1;
sop.sem_flg=0;
}
code2()

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

{
sop.sem_num=0;
sop.sem_op=1;
sop.sem_flg=0;
}
producer()
{
int i=0;
for(i=0;i<5;i++)
{
code1();
semop(semid,&sop,1);
printf("\n producing %d",i);
ptr[i]=i;
ctr[i]++;
code2();
semop(semid,&sop,1);
sleep(4);
}
}
consumer()
{
int i,j=0,var=0;
for(i=0;i<5;i++)
{
code1();
semop(semid,&sop,1);
j=ctr[i];
if(j<=0)
{
code2();
semop(semid,&sop,1);
printf("buffer empty");
sleep(4);
}
else

{
var=ptr[i];
j--;
printf("\n consumer %d",var);

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

code2();
semop(semid,&sop,1);
sleep(4);
}
}
}
OUTPUT:
[sudha@linuxserver semaphores]$ ./[Link]
producer starts
consumer starts
producing 0
consuming 0
producing 1
consuming 1
producing 2
consuming 2
producing 3
consuming 3
producing 4
producer ends
consuming 4
consumer ends

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

EXPERIMENT 6.B :Readers – Writers problem using message passing.

AIM: To write a program to implement Readers-Writers problem problem using message


passing.

PROGRAME CODE :
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <pthread.h>
#define SIZE 1024
#define SHMKEY1 (key_t)24
#define SHMKEY2 (key_t)25
#define SEMKEY1 (key_t)26
#define SEMKEY2 (key_t)27
struct databuf
{
int n;
char buf[SIZE];
};
static int wrt, shmidl, readcount, mutex;
struct sembuf sp1,sp2,sv1,sv2;
struct databuf *buff;
char *count;
void writer()

{
semop(wrt,&sp1,1);
printf("\n In the writer process, pid is : %d\n", getpid());
strcpy(buff->buf,"Hello this is writer");
/*strcat(buff->buf,(char*)getpid());*/
printf("\n Writer ended");
semop(wrt,&sv1,1);
}
void reader()
{

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

char str[100];
semop(mutex,&sp2,1);
printf("\n In reader process, pid is : %d\n", getpid());
count[0]+=1;
if(count[0]==1)
{
semop(wrt,&sp1,1);
}
semop(mutex,&sv2,1);
strcpy(str,buff->buf);
printf("\n no. of readers in critical section are %d ", count[0]);
printf("\n read message is %s, my id =%d",str, getpid());
semop(mutex,&sp2,1);
count[0]-=1;
printf("\n no. of readers in critical section are %d", count[0]);
if(count[0]==0)
{
semop(wrt,&sv1,1);
}
semop(mutex,&sv2,1);
}
int i = 0;
void * threadfunctionread(void* param)
{
printf("\nChild Thread with id %u started\n",pthread_self());
++i;
printf("Now threads are: %d\n", i);
reader();
printf("\nChild Thread with id %u ended\n\n",pthread_self());
pthread_exit(0);
}
void * threadfunctionwrite(void* param)
{
printf("\nChild Thread with id %u started\n",pthread_self());
++i;
printf("Now threads are: %d\n", i);
writer();
printf("\nChild Thread with id %u ended\n\n",pthread_self());
pthread_exit(0);
}
main()

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

{
int p1,p2;
wrt=semget(SEMKEY1,1,IPC_CREAT|0666);
mutex=semget(SEMKEY2,1,IPC_CREAT|0666);
semctl(wrt,0,SETVAL,1);
semctl(mutex,0,SETVAL,1);
shmidl=shmget(SHMKEY1,sizeof(struct databuf),IPC_CREAT|0666);
readcount=shmget(SHMKEY2,2,IPC_CREAT|0666);
count=(char *)shmat(readcount,0,0);
count[0]=0;
buff=(struct databuf*)shmat(shmidl,0,0);
sp1.sem_num=0;
sp1.sem_op=-1;
sp1.sem_flg=0;
sv1.sem_num=0;
sv1.sem_op=1;
sv1.sem_flg=0;
sp2.sem_num=0;
sp2.sem_op=-1;
sp2.sem_flg=0;
sv2.sem_num=0;
sv2.sem_op=1;
sv2.sem_flg=0;
pthread_t t1, t2, t3, t4, t5;
printf("\nMain thread id is %u\n\n",pthread_self());
pthread_create(&t1, NULL, threadfunctionread, NULL);
pthread_create(&t2, NULL, threadfunctionwrite, NULL);
pthread_create(&t3, NULL, threadfunctionread, NULL);
pthread_create(&t4, NULL, threadfunctionread, NULL);
pthread_create(&t5, NULL, threadfunctionread, NULL);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
pthread_join(t4, 0);
pthread_join(t5, 0);
semctl( wrt, 0, IPC_RMID, NULL );
semctl( mutex, 0, IPC_RMID, NULL );
shmctl( shmidl, IPC_RMID, NULL );
shmctl( readcount, IPC_RMID, NULL );
printf("\nMain Thread with id %u ended\n",pthread_self());
}

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

OUTPUT:
[sudha@linuxserver ~]$ cc rewriters.c -pthread
[sudha@linuxserver ~]$ ./[Link]
Main thread id is 3086821056
Child Thread with id 3086818192 started
Now threads are: 1
In reader process, pid is : 12307
Child Thread with id 3044858768 started
Now threads are: 2
In reader process, pid is : 12307
no. of readers in critical section are 2
read message is , my id =12307
no. of readers in critical section are 1
Child Thread with id 3044858768 ended
Child Thread with id 3055348624 started
Now threads are: 3
In reader process, pid is : 12307
no. of readers in critical section are 2
read message is , my id =12307
no. of readers in critical section are 1
Child Thread with id 3055348624 ended
Child Thread with id 3076328336 started
Now threads are: 4
Child Thread with id 3065838480 started
Now threads are: 5
In reader process, pid is : 12307
no. of readers in critical section are 2
read message is , my id =12307
no. of readers in critical section are 1
Child Thread with id 3065838480 ended
no. of readers in critical section are 1
read message is , my id =12307
no. of readers in critical section are 0
Child Thread with id 3086818192 ended
In the writer process, pid is : 12307
Writer ended
Child Thread with id 3076328336 ended
Main Thread with id 3086821056 ended

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

EXPERIMENT 6.C :Dinning philosopher problem using semaphore

AIM: To write a program to implement Dinning philosopher problem using semaphore

PROGRAM DESCRIPTION:

The program implements Dining philosopher problem which is a circular permutation based
synchronization problem using Semaphores and shared [Link] dining-philosophers
problem is considered a classic synchronization because it is an example of a large class of
concurrency-control problems. It is a simple representation of the need to allocate several
resources among several processes in a deadlock-free and starvation-free manner. Consider
five
philosophers who spend their lives thinking and eating. The philosophers share a circular
tablesurrounded by five chairs, each belonging to one philosopher. In the center of the table is
a bowlof rice, and the table is laid with five single chopsticks .When a philosopher thinks, she
does notinteract with her colleagues. From time to time, a philosopher gets hungry and tries to
pick upthe two chopsticks that are closest to her (the chopsticks that are between her and her
left andright neighbors). A philosopher may pick up only one chopstick at a time. Obviously,
she cannotpick up a chopstick that is already in the hand of a neighbor. When a hungry
philosopher hasboth her chopsticks at the same time, she eats without releasing her chopsticks.
When she isfinished eating, she puts down both of her chopsticks and starts thinking again.
One simplesolution is to represent each chopstick with a semaphore. A philosopher tries to grab
a chopstickby executing a wait () operation on that semaphore; she releases her chopsticks by
executing thesignal() operation on the appropriate semaphores. Thus, the shared data are
semaphorechopstick[5]; where all the elements of chopstick are initialized to 1. Use an
asymmetricsolution; that is, an odd philosopher picks up first her left chopstick and then her
right chopstick,
whereas an even philosopher picks up her right chopstick and then her left chopstick

ALGORITHM :

The structure of philosopher i---


do
{
wait (chopstick [i] );
wait(chopstick [(i + 1) % 5] ) ;
.………
// eat
………..
signal(chopstick [i]);
signal(chopstick [(i + 1) % 5]);
// think
} while (TRUE);

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

PROGRAME CODE :
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
static int chopstick;
struct sembuf sop;
int main()
{
int p1,p2,p3;
chopstick=semget((key_t)0X25,5,IPC_CREAT|0666);
semctl(chopstick,0,SETVAL,1);
semctl(chopstick,1,SETVAL,1);
semctl(chopstick,2,SETVAL,1);
semctl(chopstick,3,SETVAL,1);
semctl(chopstick,4,SETVAL,1);
p1=fork();
p2=fork();
// printf("%d%d",p1,p2);
if(p1==0)
{
if(p2==0)
{
p3=fork();
if(p3==0)
{
sleep(2);
philosopher(2);
}
else
{
sleep(3);
philosopher(3);
}
}
else
{
sleep(1);
philosopher(4);
}

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

}
else
{
if(p2==0)
{
sleep(2);
philosopher(1);
}
else
{
sleep(4);
philosopher(0);
}
}}
philosopher(int i)
{
while(1)
{
if(i==0||i==2||i==4)
{
printf("\n philosopher %d is thinking",i);
sleep(5);
wait_b(chopstick,i);
wait_b(chopstick,((i+1)%5));
printf("\n philosopher %d has acquired chopsticks",i);
sleep(5);
printf("\n philosopher %d is eating",i);
sleep(5);
signal_b(chopstick,i);
signal_b(chopstick,((i+1)%5));
printf("\n philosopher %d has released or returned the chopstick",i);
sleep(5);
}
else
{
printf("\n philosopher %d is thinking",i);
sleep(5);
wait_b(chopstick,((i+1)%5));
wait_b(chopstick,i);
printf("\nphilosopher %d has acquired both chopstick",i);
sleep(5);

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

printf("\nphilospher %d is eating");
sleep(5);
signal_b(chopstick,((i+1)%5));
signal_b(chopstick,i);
printf("\n philosopher %d has released chopsticks",i);
sleep(5);
}
}
}
wait_b(int semid,int semnum)
{
sop.sem_num=semnum;
sop.sem_op=-1;
sop.sem_flg=0;
semop(semid,&sop,1);
}
signal_b(int semid,int semnum)
{
sop.sem_num=semnum;
sop.sem_op=1;
sop.sem_flg=0;
semop(semid,&sop,1);
}
OUTPUT:
[sudha@linuxserver ~]$ ./[Link]
philosopher 4 is thinking
philosopher 2 is thinking
philosopher 2 has acquired chopsticks
philosopher 2 is eating
philosopher 2 has released or returned the chopstick
philosopher 1 is thinking
philosopher 1 has acquired both chopstick
philospher 1 is eating
philosopher 1 has released chopsticks
philosopher 0 is thinking
philosopher 0 has acquired chopsticks
philosopher 0 is eating
philosopher 0 has released or returned the chopstick
philosopher 4 has acquired chopsticks
philosopher 4 has released or returned the chopstick[sudha@linuxserver ~]$
philosopher 3 is thinking

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

EXPERIMENT 7 : Bankers algorithm for Deadlock detection and avoidance

AIM: To write a program to implement Bankers algorithm for Deadlock detection and
avoidance

PROGRAM DESCRIPTION:

The Banker's algorithm, sometimes referred to as the detection algorithm, is a resource


allocation and deadlock avoidance algorithm developed by Edsger Dijkstra that tests for safety
by simulating the allocation of predetermined maximum possible amounts of all
resources, and then makes an "s-state" check to test for possible deadlock conditions for all
other pending activities, before deciding whether allocation should be allowed to continue.
The algorithm was developed in the design process for the THE operating system and originally
described (in Dutch) in EWD108. [1] When a new process enters a system, it must declare the
maximum number of instances of each resource type that it may ever claim; clearly, that
number may not exceed the total number of resources in the system. Also, when a process gets
all its requested resources it must return them in a finite amount of time.

ALGORITHM:

Step 1: Start the Program

Step 2:Obtain the required data through char and int datatypes.

Step 3:Enter the filename,index block.

Step 4: Print the file name index loop.

Step 5:File is allocated to the unused index blocks

Step 6: This is allocated to the unused linked allocation.

Step 7: Stop the execution

PROGRAM CODE:

#include <stdio.h>

#include <stdlib.h>

intmain()

intMax[10][10], need[10][10], alloc[10][10], avail[10], completed[10], safeSequence[10];

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

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++)

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]);

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

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])

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

process = -1;

break; } } }

if(process != -1)

break;

if(process != -1)

printf("\nProcess %d runs to completion!", process + 1);

safeSequence[count] = process + 1;

count++;

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");

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

} else

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

OUTPUT

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

EXPERIMENT 8: Implement page replacement algorithms (a) FIFO (b) LRU

AIM: To write a C program to implement page replacement FIFO (First In First Out)
algorithm

PROGRAM DESCRIPTION

Page replacement is basic to demand paging. It completes the separation between logical
memory and physical memory. With this mechanism, an enormous virtual memory can be
provided for programmers on a smaller physical memory. There are many different page-
replacement algorithms. Every operating system probably has its own replacement scheme. A
FIFO replacement algorithm associates with each page the time when that page was brought
into memory. When a page must be replaced, the oldest page is chosen. If the recent past is
used as an approximation of the near future, then the page that has not been used for the longest
period of time can be replaced. This approach is the Least Recently Used (LRU) algorithm.
LRU replacement associates with each page the time of that page's last use. When a page must
be replaced, LRU chooses the page that has not been used for the longest period of time. Least
frequently used (LFU) page-replacement algorithm requires that the page with the smallest
count be replaced. The reason for this selection is that an actively used page should have a large
reference count.

ALGORITHM:

Step 1: Start the Program

Step 2:Obtain the required data through char and in datatypes.

Step 3:Enter the filename,index block.

Step 4: Print the file name index loop.

Step 5:File is allocated to the unused index blocks

Step 6: This is allocated to the unused linked allocation.

Step 7: Stop the execution

PROGRAM CODE

#include<stdio.h>

int main()

int i,j,n,a[50],frame[10],no,k,avail,count=0;

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

printf("\nenter the length of the Reference string:\n");

scanf("%d",&n);

printf("\n enter the reference string:\n");

for(i=1;i<=n;i++)

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

printf("\n enter the number of Frames:");

scanf("%d",&no);

for(i=0;i<no;i++)

frame[i]= -1;

j=0;

printf("\tref string\t page frames\n");

for(i=1;i<=n;i++)

printf("%d\t\t",a[i]);

avail=0;

for(k=0;k<no;k++)

if(frame[k]==a[i])

avail=1;

if (avail==0)

frame[j]=a[i];

j=(j+1)%no;

count++;

for(k=0;k<no;k++)

printf("%d\t",frame[k]);

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

printf("\n\n");

printf("Page Fault Is %d",count);

return 0;

output:-

enter the length of the Reference string:

20

enter the reference string:

7 0 1 2 030423 0321 20 1 7 0 1

enter the number of Frames:3

ref string page frames

7 7 -1 -1

0 7 0 -1

1 7 0 1

2 2 0 1

3 2 3 1

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

0 2 3 0

4 4 3 0

2 4 2 0

3 4 2 3

0 0 2 3

1 0 1 3

2 0 1 2

7 7 1 2

0 7 0 2

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

1 7 0 1

Page Fault Is 15

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

B ) LRU

AIMTo write a C program to implement page replacement LRU (Least Recently Used)
algorithm.

ALGORITHM:

Step 1: Start the Program

Step 2:Obtain the required data through char and int datatypes.

Step 3:Enter the filename,index block.

Step 4: Print the file name index loop.

Step 5:Fill is allocated to the unused index blocks

Step 6: This is allocated to the unused linked allocation.

Step 7: Stop the execution

PROGRAM CODE

#include<stdio.h>

int findLRU(int time[], int n){

int i, minimum = time[0], pos = 0;

for(i = 1; i < n; ++i){

if(time[i] < minimum){

minimum = time[i];

pos = i;

return pos;

int main()

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

int no_of_frames, no_of_pages, frames[10], pages[30], counter = 0, time[10], flag1, flag2, i,


j, pos,

faults = 0;

printf("Enter number of frames: ");

scanf("%d", &no_of_frames);

printf("Enter number of pages: ");

scanf("%d", &no_of_pages);

printf("Enter reference string: ");

for(i = 0; i < no_of_pages; ++i){

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

for(i = 0; i < no_of_frames; ++i)

frames[i] = -1;

for(i = 0; i < no_of_pages; ++i){

flag1 = flag2 = 0;

for(j = 0; j < no_of_frames; ++j){

if(frames[j] == pages[i]){

counter++;

time[j] = counter;

flag1 = flag2 = 1;

break;

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

if(flag1 == 0){

for(j = 0; j < no_of_frames; ++j){

if(frames[j] == -1){

counter++;

faults++;

frames[j] = pages[i];

time[j] = counter;

flag2 = 1;

break;

}} }

if(flag2 == 0){

pos = findLRU(time, no_of_frames);

counter++;

faults++;

frames[pos] = pages[i];

time[pos] = counter;

printf("\n");

for(j = 0; j < no_of_frames; ++j){

printf("%d\t", frames[j]);

}}

printf("\n\nTotal Page Faults = %d", faults);

return 0;

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

OUTPUT:

Enter number of frames: 3

Enter number of pages: 10

Enter reference string: 4 7 6 1 7 6 1 2 7 2

4 -1

-1

47

-1

47

17

17

17

17

12

12

12

Total Page Faults = 6

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

C) LFU

#include<stdio.h>
void print(int frameno,int frame[])
{
int j;
for(j=0;j<frameno;j++)
printf("%d\t",frame[j]);
printf("\n");
}
int main()
{
int i,j,k,n,page[50],frameno,frame[10],move=0,flag,count=0,count1[10]={0},
repindex, leastcount;
float rate;
printf("Enter the number of pages\n");
scanf("%d",&n);
printf("Enter the page reference numbers\n");
for(i=0;i<n;i++)
scanf("%d",&page[i]);
printf("Enter the number of frames\n");
scanf("%d",&frameno);
for(i=0;i<frameno;i++)
frame[i]=-1;
printf("Page reference string\tFrames\n");
for(i=0;i<n;i++)
{
printf("%d\t\t\t",page[i]);
flag=0;
for(j=0;j<frameno;j++)
{
if(page[i]==frame[j])
{
flag=1;
count1[j]++;
printf("No replacement\n");
break;
}
}
if(flag==0&&count<frameno)
{
frame[move]=page[i];
count1[move]=1;
move=(move+1)%frameno;
count++;
print(frameno,frame);
}

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

else if(flag==0)
{
repindex=0;
leastcount=count1[0];
for(j=1;j<frameno;j++)
{
if(count1[j]<leastcount)
{
repindex=j;
leastcount=count1[j];
}
}

frame[repindex]=page[i];
count1[repindex]=1;
count++;
print(frameno,frame);
}
}
rate=(float)count/(float)n;
printf("Number of page faults is %d\n",count);
printf("Fault rate is %f\n",rate);
return 0;
}

Output:

Enter the number of pages

Enter the page reference numbers

Enter the number of frames

Page reference string Frames

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

7 7 -1 -1

4 7 4 -1

1 7 4 1

2 2 4 1

3 3 4 1

Number of page faults is 5

Fault rate is 1.000000

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

EXPERIMENT 9 : Write C programs to simulate implementation of Disk Scheduling Algorithms:


FCFS, SSTF

b) FCFS

#include<stdio.h>

#include <stdlib.h>

int main(){

int queue[100], q_size, head, seek =0, diff;

float avg;

printf("%s\n", "***FCFS Disk Scheduling Algorithm***");

printf("%s\n", "Enter the size of the queue");

scanf("%d", &q_size);

printf("%s\n", "Enter queue elements");

for(int i=1; i<=q_size; i++){

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

printf("%s\n","Enter initial head position");

scanf("%d", &head);

queue[0]=head;

for(int j=0; j<=q_size-1; j++){

diff = abs(queue[j]-queue[j+1]); seek += diff;

printf("Move from %d to %d with Seek %d\n",queue[j],queue[j+1],diff);

printf("\nTotalseek time is %d\t",seek);

avg = seek/(float)q_size;

printf("\nAverage seek time is %f\t", avg);

return 0;

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

OUTPUT-

***FCFS Disk Scheduling Algorithm***

Enter the size of the queue

Enter queue elements

23 1 5 20

Enter initial head position

Move from 1 to 23 with Seek 22

Move from 23 to 1 with Seek 22

Move from 1 to 5 with Seek 4

Move from 5 to 20 with Seek 15

Totalseek time is 63

Average seek time is 15.750000

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

B) SSTF

#include<stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int queue[100], queue2[100], q_size, head, seek=0, temp;
float avg;
printf("%s\n", "-----SSTF Disk Scheduling Algorithm ----- ");
printf("%s\n", "Enter the size of the queue");
scanf("%d", &q_size);
printf("%s\n", "Enter queue elements");
for(int i=0; i<q_size; i++){
scanf("%d",&queue[i]);
}
printf("%s\n","Enter initial head position");
scanf("%d", &head);
//get distance from head of elems in queue
for(int i=0; i<q_size; i++){
queue2[i] = abs(head-queue[i]);
}
//swap elems based on their distance from each other
for(int i=0; i<q_size; i++){
for(int j=i+1; j<q_size;j++){
if(queue2[i]>queue2[j]){
temp = queue2[i];
queue2[i]=queue2[j];
queue2[j]=temp;
temp=queue[i];
queue[i]=queue[j];
queue[j]=temp;
}
}
}
for(int i=1; i<q_size; i++){
seek = seek+abs(head-queue[i]);
head = queue[i];
}
printf("\nTotal seek time is %d\t",seek);

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

avg = seek/(float)q_size;
printf("\nAverage seek time is %f\t", avg);
return 0;
}

Output:
-----SSTF Disk Scheduling Algorithm-----
Enter the size of the queue
5
Enter queue elements
20
55
76
43
90
Enter initial head position
35

Total seek time is 85


Average seek time is 17.000000

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

LAB QUESTIONS & ASSIGNMENTS

WEEK 1 QUESTIONS

1. Define operating system?


2. What are the different types of operating systems?
3. Define a process?
4. What is CPU Scheduling?
5. Define arrival time, burst time, waiting time, turnaround time?
6. What is the advantage of round robin CPU scheduling algorithm?
7. Which CPU scheduling algorithm is for real-time operating system?
8. In general, which CPU scheduling algorithm works with highest waiting time?
9. Is it possible to use optimal CPU scheduling algorithm in practice?
10. What is the real difficulty with the SJF CPU scheduling algorithm?

ASSIGNMENT QUESTIONS
1. Write a C program to implement round robin CPU scheduling algorithm for the
following given scenario. All the processes in the system are divided into two
categories – system processes and user processes.
2. System processes are to be given higher priority than user processes. Consider the
time quantum size for the system processes and user processes to be 5 msec and 2
msec respectively.
3. Write a C program to simulate pre-emptive SJF CPU scheduling algorithm.

WEEK 2 QUESTIONS
1. What is multi-level queue CPU Scheduling?
2. Differentiate between the general CPU scheduling algorithms like FCFS, SJF etc and
multi-level queue CPU Scheduling?
3. What are CPU-bound I/O-bound processes?
4. What are the parameters to be considered for designing a multilevel feedback queue
scheduler?
5. Differentiate multi-level queue and multi-level feedback queue CPU scheduling
algorithms?
6. What are the advantages of multi-level queue and multi-level feedback queue CPU
scheduling algorithms?

ASSIGNMENT QUESTIONS
1. Write a C program to simulate multi-level queue scheduling algorithm considering the
following scenario.
2. All the processes in the system are divided into two categories – system processes and
user processes. System processes are to be given higher priority than user processes.
Consider each process priority to be from 1 to 3. Use priority scheduling for the
processes in each queue.

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

WEEK 3 QUESTIONS
1. Define file?
2. What are the different kinds of files?
3. What is the purpose of file allocation strategies?
4. Identify ideal scenarios where sequential, indexed and linked file allocation strategies
are most appropriate?
5. What are the disadvantages of sequential file allocation strategy?
6. What is an index block?
7. What is the file allocation strategy used in UNIX?

ASSIGNMENT QUESTIONS
1. Write a C program to simulate a two-level index scheme for file allocation?

WEEK 4 QUESTIONS
1. What is the purpose of memory management unit?
2. Differentiate between logical address and physical address?
3. What are the different types of address binding techniques?
4. What is the basic idea behind contiguous memory allocation?
5. How is dynamic memory allocation useful in multiprogramming operating systems?
6. Differentiate between equal sized and unequal sized MFT schemes?
7. What is the advantage of MVT memory management scheme over MFT?

ASSIGNMENT QUESTIONS
1. Write a C program to simulate MFT memory management scheme with unequal sized
partitions.

WEEK 5 QUESTIONS
1. Differentiate between the memory management schemes MFT and MVT?
2. What is dynamic memory allocation?
3. What is external fragmentation?

4. Which of the dynamic contiguous memory allocation strategies suffer with external
fragmentation?
5. What are the possible solutions for the problem of external fragmentation?
6. What is 50-percent rule?
7. What is compaction?
8. Which of the memory allocation techniques first-fit, best-fit, worst-fit is efficient?
Why?

ASSIGNMENT QUESTIONS
1. Write a C program to implement compaction technique.

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

WEEK 6 QUESTIONS
1. What are the advantages of noncontiguous memory allocation schemes?
2. What is the process of mapping a logical address to physical address with respect to
the paging memory management technique?
3. Define the terms – base address, offset?

WEEK 7 QUESTIONS
1. Differentiate between paging and segmentation memory allocation techniques?
2. What is the purpose of page table?
3. Whether the paging memory management technique suffers with internal or external
fragmentation problem. Why?
4. What is the effect of paging on the overall context-switching time?

ASSIGNMENT QUESTIONS
1. Write a C program to simulate two-level paging technique.
2. Write a C program to simulate segmentation memory management technique.

WEEK 8 QUESTIONS
1. Define directory?
2. Describe the general directory structure?
3. List the different types of directory structures?
1. Which of the directory structures is efficient? Why?
2. Which directory structure does not provide user-level isolation and protection?
3. What is the advantage of hierarchical directory structure?

ASSIGNMENT QUESTIONS
1. Write a C to simulate acyclic graph directory structure?
2. Write a C to simulate general graph directory structure?

WEEK 8 QUESTIONS
1. Define resource. Give examples.
2. What is deadlock?
3. What are the conditions to be satisfied for the deadlock to occur?
1. How can be the resource allocation graph used to identify a deadlock situation?
2. How is Banker’s algorithm useful over resource allocation graph technique?
3. Differentiate between deadlock avoidance and deadlock prevention?

ASSIGNMENT QUESTIONS
1. Write a C program to implement deadlock detection technique for the following
scenarios?
a. Single instance of each resource type
b. Multiple instances of each resource type

WEEK 9 QUESTIONS

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

2. What is disk scheduling?


3. List the different disk scheduling algorithms?
4. Define the terms – disk seek time, disk access time and rotational latency?

5. What is the advantage of C-SCAN algorithm over SCAN algorithm?


6. Which disk scheduling algorithm has highest rotational latency? Why?

ASSIGNMENT QUESTIONS
1. Write a C program to implement SSTF disk scheduling algorithm?

WEEK 10 QUESTIONS
1. Define the concept of virtual memory?
2. What is the purpose of page replacement?
3. Define the general process of page replacement?
4. List out the various page replacement techniques?
5. What is page fault?
6. Which page replacement algorithm suffers with the problem of Belady’s
anomaly?
7. Define the concept of thrashing? What is the scenario that leads to the situation of
thrashing?

ASSIGNMENT QUESTIONS
1. Write a C program to simulate LRU-approximation page replacement algorithm?
a. Additional-Reference bits algorithm
b. Second-chance algorithm

WEEK 11 QUESTIONS
1. What are the benefits of optimal page replacement algorithm over other page
replacement algorithms?

2. Why can’t the optimal page replacement technique be used in practice?

3. What is the need for process synchronization?


4. Define a semaphore?
5. Define producer-consumer problem?

6. Discuss the consequences of considering bounded and unbounded buffers in


producer-consumer problem?
7. Can producer and consumer processes access the shared memory concurrently? If not
which technique provides such a benefit?

ASSIGNMENT QUESTIONS
1. Write a C program to simulate producer-consumer problem using message-passing
system.

[Link]-Sem CSE Stanley College of Engg & Tech for Women


STANLEY COLLEGE OF ENGINEERING AND TECHNOLOGY FOR WOMEN OS LAB

WEEK 12 QUESTIONS
1. Differentiate between a monitor, semaphore and a binary semaphore?
2. Define clearly the dining-philosophers problem?
3. Identify the scenarios in the dining-philosophers problem that leads to the deadlock
situations?

ASSIGNMENT QUESTIONS
1. Write a C program to simulate readers-writers problem using monitors

[Link]-Sem CSE Stanley College of Engg & Tech for Women

You might also like