0% found this document useful (0 votes)
2 views

Lab Programs OS

The document contains multiple programming tasks including Shell scripts for checking palindromes, generating prime numbers, finding the largest number in an array, and adding matrices. It also includes C programs implementing various scheduling algorithms such as SJF pre-emptive, Priority pre-emptive, Round Robin, and Priority non-preemptive scheduling. Each task is accompanied by code snippets demonstrating the implementation of the respective algorithms and functionalities.

Uploaded by

kefivek340
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lab Programs OS

The document contains multiple programming tasks including Shell scripts for checking palindromes, generating prime numbers, finding the largest number in an array, and adding matrices. It also includes C programs implementing various scheduling algorithms such as SJF pre-emptive, Priority pre-emptive, Round Robin, and Priority non-preemptive scheduling. Each task is accompanied by code snippets demonstrating the implementation of the respective algorithms and functionalities.

Uploaded by

kefivek340
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 25

1a.

Write a Shell program to check whether a given string is palindrome or not


Program:
#Shell script to check whether a given string is palindrome or not
#!/bin/bash
echo "Enter the string: "
read str
echo "The given string is $str"
len=${#str}
echo "Length of string is $len"
for((i=len-1;i>=0;i--))
do
rstr=$rstr${str:i:1}
done
echo "Reversed string is $rstr"
if [ $str == $rstr ]
then
echo "The given string is palindrome"
else
echo "The given string is not a palindrome"
fi

1b. Implement SJF pre-emptive scheduling algorithm by defining process structure


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

struct pcb{
int pid, at, bt, ct, tt, wt;
};

void main(){
int n;
printf("Enter the num. of processes>> ");
scanf("%d", &n);

struct pcb p[n];


int btRemain[n];
printf("PID AT BT\n");
for(int i = 0; i<n; ++i){
scanf("%d%d%d", &p[i].pid, &p[i].at, &p[i].bt);
btRemain[i] = p[i].bt;
}

int min, index, completed = 0, curtime = 0, tottt = 0, totwt = 0, pid[40],


ct[40], len = 0, j = 0, prev = -2;

// Initializing completed array to 0


int *isCompleted = (int *)calloc(sizeof(int), n);

printf("\n\n");
while (completed < n){
int min = 99999, index = -1;

for(int i = 0; i<n ; ++i){


// Select process of minimum burst time remaining
if ( p[i].at <= curtime && !isCompleted[i]){
if ( btRemain[i] < min ){
index = i;
min = btRemain[i];
}

// Select process first arrived when burst time remained is same


if ( btRemain[i] == btRemain[index]){
if ( p[i].at < p[index].at){
index = i;
min = btRemain[i];
}
}
}
}

if (index != -1){
if ( prev == curtime - 1 && pid[j-1] == p[index].pid ){
++ct[j-1];
prev = curtime;
}
else{
pid[j] = p[index].pid;
ct[j] = curtime + 1;
++len;
++j;
prev = curtime;
}
--btRemain[index];
++curtime;

if ( btRemain[index] == 0 ){
// Process execution completed
p[index].ct = curtime;
p[index].tt = p[index].ct - p[index].at;
p[index].wt = p[index].tt - p[index].bt;

totwt += p[index].wt;
tottt += p[index].tt;

++completed;
isCompleted[index] = 1;
}
}
else{
if ( prev == curtime - 1 && pid[j-1] == -1){
++ct[j-1];
prev = curtime;
}
else{
pid[j] = -1;
ct[j] = curtime + 1;
++len;
++j;
prev = curtime;
}
++curtime;
}
}

printf("\nPID\tAT\tBT\tCT\tTT\tWT\n");
for(int i = 0; i<n; ++i)
printf("%d\t%d\t%d\t%d\t%d\t%d\n", p[i].pid, p[i].at, p[i].bt, p[i].ct,
p[i].tt, p[i].wt);

printf("\n\nGantt chart >> \n");


for(int i = 0; i<len; ++i)
printf("-------");
printf("\n");
for(int i = 0; i<len; ++i){
if (pid[i] != -1)
printf(" P%d |", pid[i]);
else
printf(" IDLE |");
}
printf("\n");
for(int i = 0; i<len; ++i)
printf("-------");
printf("\n0 ");
for(int i = 0; i<len; ++i)
printf("%d ", ct[i]);
printf("\n");

printf("\n\nAvg turn around time >> %.2f\n", (float)tottt/n);


printf("Avg waiting time >> %.2f\n", (float)totwt/n);
}

-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-
2a. Write a Shell program to generate prime number in the given range
Program:

2b. Implement Priority Pre-emptive scheduling algorithm by defining process


structure.
Program:
#include<stdio.h>
#include<stdlib.h>

struct pcb{
int pid, at, bt, pr, ct, tt, wt;
};

void main(){
int n;
printf("Enter num. of processes >> ");
scanf("%d", &n);

struct pcb p[n];


int btRemain[n];
printf("PID AT BT PRI\n");
for(int i = 0; i<n; ++i){
scanf("%d%d%d%d", &p[i].pid, &p[i].at, &p[i].bt, &p[i].pr);
btRemain[i] = p[i].bt;
}

// Initializing completed array to 0


int *isCompleted = (int *)calloc(sizeof(int), n);

int completed = 0, curtime = 0, totwt = 0 , tottt = 0, max, index, prev = -2,


pid[20], ct[20], j = 0, len = 0;
printf("\n");
while ( completed < n ){
max = -1, index = -1;

for(int i = 0; i<n; ++i){


// Selecting process of highest priority in current time
if ( p[i].at <= curtime && !isCompleted[i]){
if ( p[i].pr > max ){
max = p[i].pr;
index = i;
}

// for same priority select process of lowest at


if ( p[i].pr == p[index].pr ){
if ( p[i].at < p[index].at ){
index = i;
max = p[i].pr;
}
}
}
}

if ( index != -1 ){
if ( prev == curtime -1 && pid[j-1] == p[index].pid){
++ct[j-1];
prev = curtime;
}
else{
ct[j] = curtime + 1;
pid[j] = p[index].pid;
++len;
++j;
prev = curtime;
}
--btRemain[index];
++curtime;

if ( btRemain[index] == 0 ){
// If process finished execution
p[index].ct = curtime;
p[index].tt = p[index].ct - p[index].at;
p[index].wt = p[index].tt - p[index].bt;

totwt += p[index].wt;
tottt += p[index].tt;

++completed;
isCompleted[index] = 1;
}
}

else{
if ( prev == curtime -1 && pid[j-1] == -1){
++ct[j-1];
prev = curtime;
}
else{
ct[j] = curtime + 1;
pid[j] = -1;
++len;
++j;
prev = curtime;
}
++curtime;
}
}

printf("PID\tAT\tBT\tPRI\tCT\tTT\tWT\n");
for(int i = 0; i<n; ++i)
printf("%d\t%d\t%d\t%d\t%d\t%d\t%d\n", p[i].pid, p[i].at, p[i].bt, p[i].pr,
p[i].ct, p[i].tt, p[i].wt);

printf("\n\nGantt chart >> \n");


for(int i = 0; i<len; ++i)
printf("-------");
printf("\n");
for(int i = 0; i<len; ++i){
if (pid[i] != -1)
printf(" P%d |", pid[i]);
else
printf(" IDLE |");
}
printf("\n");
for(int i = 0; i<len; ++i)
printf("-------");
printf("\n0 ");
for(int i = 0; i<len; ++i)
printf("%d ", ct[i]);
printf("\n");

printf("\n\nAvg turn around time >> %.2f\n", (float)tottt/n);


printf("Avg waiting time >> %.2f\n", (float)totwt/n);
}

-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
3a. Write a Shell program to find the largest of n numbers,storing numbers in an
array
Program:
#Shell script to find the largest number in an array
#!/bin/bash
echo "Enter the elements of the array "
read -a A
echo "The elements of the array are ${A[*]}"
len=${#A[*]}
echo "The length of the array is $len"
large=${A[0]}
for((i=1;i<$len;i++))
do
if [ ${A[i]} -gt $large ]
then
large=${A[i]}
fi
done
echo "The largest element in the array is $large"

3b. Implement Round robin scheduling algorithm by defining process structure


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

struct pcb{
int pid, at, bt, ct, tt, wt;
};
int n;
int Q[20], f = -1, r = -1;

void enq(int index){


if ( f == -1)
++f;
r = (r+1)%n;
Q[r] = index;
}

int deq(){
if (f==r){
int a = f;
f = r = -1;
return Q[a];
}
else{
int a = f;
f = (f+1)%n;
return Q[a];
}
}

int isEmpty(){
if ( f==r && r == -1)
return 1;
else
return 0;
}

void main(){
printf("Enter num. of processes >> ");
scanf("%d", &n);

struct pcb p[n];


int bt[n], qt;
printf("PID AT BT\n");
for(int i = 0; i<n; ++i){
scanf("%d%d%d", &p[i].pid, &p[i].at, &p[i].bt);
bt[i] = p[i].bt;
}
printf("Enter time quantum >> ");
scanf("%d", &qt);

// Initializling inqueue array to 0


int * inqueue = (int *)calloc(sizeof(int), n);

int completed = 0, curtime = 0, index, tottt = 0, totwt = 0, pid[20], ct[20],


len = 0, j = 0;

// Sorting based on arrival time


for(int i = 0; i<n-1; ++i){
for(int j = 0; j<n-i-1; ++j){
if ( p[j].at > p[j+1].at ){
struct pcb temp = p[j+1];
p[j+1] = p[j];
p[j] = temp;

int t = bt[j+1];
bt[j+1] = bt[j];
bt[j] = t;
}
}
}

if ( p[0].at != 0 ){
pid[j] = -1;
ct[j] = p[0].at;
++j;
++len;
}

// Putting first arrived process in queue


enq(0);
inqueue[0] = 1;

while ( completed != n ){
if ( !isEmpty() ){
index = deq();

if ( p[index].bt > qt ){
p[index].bt -= qt;
curtime += qt;
}
else{
curtime += p[index].bt;
p[index].bt = 0;

p[index].ct = curtime;
p[index].tt = p[index].ct - p[index].at;
p[index].wt = p[index].tt - bt[index];

tottt += p[index].tt;
totwt += p[index].wt;

++completed;
}
}
else{
++curtime;
}

if ( p[index].pid == pid[j - 1]){


ct[j-1] = curtime;
}
else{
ct[j] = curtime;
pid[j] = p[index].pid;
++j;
++len;
}
// Selecting process which is not in queue and arrived at curtime and
putting it to ready queue
for(int i= 0; i<n && p[i].at <= curtime; ++i){
if ( p[i].bt == 0 || p[i].pid == p[index].pid || inqueue[i] )
continue;
enq(i);
inqueue[i] = 1;
}
// If bt remain of current process , put it to last in queue
if ( p[index].bt > 0 )
enq(index);
}

printf("\nPID\tAT\tBT\tCT\tTT\tWT\n");
for(int i = 0; i<n; ++i)
printf("%d\t%d\t%d\t%d\t%d\t%d\n", p[i].pid, p[i].at, bt[i], p[i].ct,
p[i].tt, p[i].wt);

printf("\n\nGantt chart >> \n");


for(int i=0; i<len; ++i)
printf("-------");
printf("\n");
for(int i = 0; i<len; ++i){
if ( pid[i] != -1 )
printf(" P%d |", pid[i]);
else
printf(" IDLE |");
}
printf("\n");
for(int i =0; i<len; ++i)
printf("-------");
printf("\n0 ");
for(int i = 0; i<len; ++i){
if ( ct[i] < 10 )
printf("%d ", ct[i]);
else
printf("%d ", ct[i]);
}

printf("\n\nAvg turn around time >> %.2f\n", (float)tottt/n);


printf("Avg waiting time >> %.2f\n", (float)totwt/n);
}

-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-
4a. Write a Shell program to find input of two matrices, add the matrices and
display their sum
Program:
#Shell Script to read two matrices,find their sum and display the same
#!/bin/bash
declare -A X
declare -A Y
declare -A Z
echo "Enter the order of matrix"
read order
echo "Enter the elements of 1st Matrix"
for((i=0;i<$order;i++))
do
for((j=0;j<$order;j++))
do
read X[$i,$j]
done
done
echo "Enter the elements of 2nd Matrix"
for((i=0;i<$order;i++))
do
for((j=0;j<$order;j++))
do
read Y[$i,$j]
done
done
echo "First Matrix:"
for((i=0;i<$order;i++))
do
for((j=0;j<$order;j++))
do
echo -ne "${X[$i,$j]} "
done
echo -ne "\n"
done
echo "Second Matrix"
for((i=0;i<$order;i++))
do
for((j=0;j<$order;j++))
do
echo -ne "${X[$i,$j]} "
done
echo -ne "\n"
done
echo "The sum of Matrices is"
for((i=0;i<$order;i++))
do
for((j=0;j<$order;j++))
do
Z[$i,$j]=$((X[$i,$j]+Y[$i,$j]))
echo -ne "${Z[$i,$j]} "
done
echo -e "\n"
done

4b. Implement Priority Non-preemptive scheduling algorithm by defining process


structure
Program
#include<stdio.h>
#include<stdlib.h>

struct pcb{
int pid, at, bt, ct, wt, tt, pr;
};

void main(){
int n;
printf("Enter num. of processes>> ");
scanf("%d", &n);
struct pcb p[n];

// Initializing completed array to 0


int * isCompleted = (int *)calloc(sizeof(int), n);
printf("PCB AT BT PRI\n");
for(int i = 0 ; i<n; ++i)
scanf("%d%d%d%d", &p[i].pid, &p[i].at, &p[i].bt, &p[i].pr);
printf("\n\n");

int completed = 0, curtime = 0, totwt = 0, tottt = 0, temp;


int pid[10], ct[10], j= 0, prev = -2, len = n;

while (completed < n){


int index = -1, m = -1;
for(int i =0; i<n ; ++i){
if ( p[i].at <= curtime && !isCompleted[i]){
// Select process of max priority
if ( m < p[i].pr ){
index = i;
m = p[i].pr;
}

// If priority is same sort based on at


if ( p[i].pr == p[index].pr ){
if (p[i].at < p[index].at){
index = i;
m = p[i].pr;
}
}
}
}

if (index != -1){
p[index].ct = curtime + p[index].bt;
p[index].tt = p[index].ct - p[index].at;
p[index].wt = p[index].tt - p[index].bt;

pid[j] = p[index].pid;
ct[j] = p[index].ct;
++j;

totwt += p[index].wt;
tottt += p[index].tt;

++completed;
if (completed == 1) temp = curtime;
curtime = p[index].ct;
isCompleted[index] = 1;
}
else{
if ( prev == curtime - 1){
++ct[j-1];
prev = curtime;
}
else{
pid[j]= -1;
ct[j] = curtime + 1;
++len;
++j;
prev = curtime;
}
++curtime;
}
}

printf("PID\tAT\tBT\tPRI\tCT\tTT\tWT\n");
for(int i = 0; i<n; ++i)
printf("%d\t%d\t%d\t%d\t%d\t%d\t%d\n", p[i].pid, p[i].at, p[i].bt, p[i].pr,
p[i].ct, p[i].tt, p[i].wt );

printf("\n\nGantt Chart >> \n");


for(int i = 0; i<len; ++i)
printf("-------");
printf("\n");
for(int i= 0; i<len; ++i){
if ( pid[i] != -1 )
printf(" P%d |", pid[i]);
else
printf(" IDLE |");
}
printf("\n");
for(int i = 0; i<len; ++i)
printf("-------");
printf("\n");
printf("0 ");
for(int i = 0; i<len; ++i)
printf("%d ", ct[i]);
printf("\n\n");

printf("\nAvg turn around time >> %.2f\n", (float)tottt/n);


printf("Avg waiting time >> %.2f\n", (float)totwt/n);
}
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-
5a. Write a program to perform the following tasks using I/O system calls for file
I/O
a. Read First 10 characters from the file
b. Skiiping 5 characters from the current position in the file
c. Going to 5th last character in the file
d. Going to 3rd character in the file
Program:
/*C program to perform the following file operation*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#define BUFFER 30
void main()
{
int fd,n;
char buffer[BUFFER],fname[BUFFER];
printf("\nEnter the file name: ");
scanf("%s",fname);
fd=open(fname,O_RDWR);
printf("\nFile Descriptor is %d",fd);
if(fd==-1)
{
printf("\nFailed to open the file");
exit(0);
}
printf("\nReading first characters 10 in the file");
n=read(fd,buffer,10);
write(1,buffer,n);
printf("\nSkipping 5 characters from current position");
lseek(fd,5,SEEK_CUR);
n=read(fd,buffer,10);
write(1,buffer,n);
printf("\nGoing 10 characters before the current position in the file: ");
lseek(fd,-10,SEEK_CUR);
n=read(fd,buffer,10);
write(1,buffer,n);
printf("\nGoing to the fifth last character in the file");
lseek(fd,-5,SEEK_END);
n=read(fd,buffer,5);
write(1,buffer,n);
printf("\nGoing to third character in the file");
lseek(fd,3,SEEK_SET);
n=read(fd,buffer,5);
write(1,buffer,n);
printf("\n\n");
}

5b. Implement FCFS scheduling by defining process structure


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

struct pcb{
int pid, at, bt, ct, tt, wt;
};

void main(){
int n;
printf("Enter num of processes >> ");
scanf("%d", &n);

struct pcb p[n];

printf("PID AT BT\n");
for(int i= 0; i<n; ++i)
scanf("%d%d%d", &p[i].pid, &p[i].at, &p[i].bt);

// Initializing completed array to 0


int * isCompleted = (int *)calloc(sizeof(int),n);

int min, index , completed = 0, curtime = 0, pid[20], ct[20], len = n, prev = -


2, tottt = 0, totwt = 0, j = 0;

while ( completed != n ){
index = -1, min = 99999;

// Selection of process of minimum at


for(int i = 0; i<n; ++i){
if (p[i].at <= curtime && !isCompleted[i]){
if ( min > p[i].at){
index = i;
min = p[i].at;
}
}
}

if ( index != -1 ){
p[index].ct = p[index].bt + curtime;
p[index].tt = p[index].ct - p[index].at;
p[index].wt = p[index].tt - p[index].bt;

tottt += p[index].tt;
totwt += p[index].wt;

ct[j] = p[index].ct;
pid[j] = p[index].pid;
++j;

curtime = p[index].ct;
++completed;
isCompleted[index] = 1;
}
else{
if (prev == curtime - 1){
++ct[j-1];
prev = curtime;
}
else{
pid[j] = -1;
ct[j] = curtime + 1;
++len;
++j;
prev = curtime;
}
++curtime;
}
}

printf("PID\tAT\tBT\tCT\tTT\tWT\n");
for(int i = 0; i<n; ++i)
printf("%d\t%d\t%d\t%d\t%d\t%d\n", p[i].pid, p[i].at, p[i].bt, p[i].ct,
p[i].tt, p[i].wt);

printf("\nGantt Chart >> \n");


for(int i = 0; i<len; ++i)
printf("-------");
printf("\n");
for(int i = 0; i<len; ++i){
if ( pid[i] != -1 )
printf(" P%d |", pid[i]);
else
printf(" IDLE |");
}
printf("\n");
for(int i = 0; i<len; ++i)
printf("-------");
printf("\n");
printf("0 ");
for(int i = 0; i<len; ++i)
printf("%d ", ct[i]);

printf("\n\nAvg turn around time >> %.2f\n", (float)tottt/n);


printf("Avg waiting time >> %.2f\n", (float)totwt/n);
}
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
6a. C program to show Zombie process and Orphan process
Program
//Zombie process
/*C program to demonstrate Zombie and orphan process and display appropriate
outputs for the same*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
void main()
{
pid_t child,my,parent;
child=fork();
if(child<0)
{
printf("\nFork Failed");
}
if(child==0)
{
printf("\n[CHILD]This is the child process");
my=getpid();
parent=getppid();
printf("\n[CHILD]My pid is %d",my);
printf("\n[CHILD]My parent's pid is %d",parent);
printf("\n[CHILD]Termination of the Child process");
}
else{
printf("\n[PARENT]This is the parent process");
my=getpid();
parent=getppid();
printf("\n[PARENT]My pid is %d",my);
printf("\n[PARENT]My Parent's pid is %d",parent);
printf("\n[PARENT]Sleeping for 10 seconds");
sleep(10);
printf("\n[PARENT]Child process with pid %d has been termianted,but it has
an entry in the process table and such process is called as Zombie process",child);

}
}

//Orphan process
/*C program to show Orphan process*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
void main()
{
pid_t my,child,parent;
child=fork();
if(child<0)
{
printf("\nFork unsuccuessfull");
}
if(child==0)
{
printf("\n[CHILD]This is the Child process");
my=getpid();
parent=getppid();
printf("\n[CHILD]My pid is %d",my);
printf("\n[CHILD]My parent's pid is %d",parent);
sleep(10);
printf("\n[CHILD]My parent has been terminated and now with the termination
of my process I am adopted by Init process with pid %d",parent);
}
else
{
printf("\n[PARENT]This is Parent Process");
my=getpid();
parent=getppid();
printf("\n[PARENT]My pid is %d",my);
printf("\n[PARENT]My parent's pid is %d",parent);
printf("\n[PARENT]Parent process finished its task and hence is
terminating");
exit(0);
}
}

6b.Implement SJF Non-preemptive scheduling algorithm by defining process structure.


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

struct pcb {
int pid, at, bt, wt, tt, ct;
};

void main(){
int n;
printf("Enter the number of processes >> ");
scanf("%d",&n);
struct pcb p[n];

printf("PID AT BT\n");
for(int i = 0 ; i<n ; ++i)
scanf("%d%d%d", &p[i].pid, &p[i].at, &p[i].bt);

// Initializing is completed array to 0


int * isCompleted = (int *)calloc(sizeof(int), n);

int curtime = 0, completed = 0, totwt = 0, tottt = 0, temp;


int pid[10], ct[10], j = 0, prev = -2, len = n;

while ( completed < n ){


// Finding process from ready queue
int min = 999999, index = -1;
// Seleting process that is arrived and is not completed
for(int i = 0; i<n; ++i){
if ( p[i].at <= curtime && !isCompleted[i]){
if (p[i].bt < min){
min = p[i].bt;
index = i;
}

// If two process has same bt, select process that has arrived first
if (p[i].bt == min){
if (p[i].at < p[index].at){
index = i;
min = p[i].bt;
}
}
}
}

if ( index != -1 ){
p[index].ct = curtime + p[index].bt;
p[index].tt = p[index].ct - p[index].at;
p[index].wt = p[index].tt - p[index].bt;
tottt += p[index].tt;
totwt += p[index].wt;

pid[j] = p[index].pid;
ct[j] = p[index].ct;
++j;

isCompleted[index] = 1;
++completed;
if (completed == 1) temp = curtime;
curtime = p[index].ct;
}
else{
// CPU idle
if ( prev == curtime - 1 ){
++ct[j-1];
prev = curtime;
}
else{
pid[j] = -1;
ct[j] = curtime + 1;
++j;
prev = curtime;
++len;
}
++curtime;
}
}

printf("\n\nPID\tAT\tBT\tCT\tTT\tWT\n");
for(int i = 0; i<n ; ++i)
printf("%d\t%d\t%d\t%d\t%d\t%d\n", p[i].pid, p[i].at, p[i].bt, p[i].ct,
p[i].tt, p[i].wt);

printf("\nGantt chart\n");
for(int i = 0;i<len; ++i)
printf("-------");
printf("\n");
for(int i = 0;i<len; ++i){
if ( pid[i] != -1)
printf(" P%d |", pid[i]);
else
printf(" IDLE |");
}
printf("\n");
for(int i = 0;i<len; ++i)
printf("-------");
printf("\n");
printf("0 ");
for(int i = 0;i<len; ++i)
printf("%d ", ct[i]);
printf("\n");

printf("\n\nAvg turn around time >> %.2f\n", (float)tottt/n);


printf("Avg waiting time >> %.2f\n", (float)totwt/n);
}

-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-
7a. Write a program to simulate grep command using system calls
Program:
/*C program to simulate grep command*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
char fn[10],pat[10],temp[20];
FILE *fp;
printf("\nEnter the file name: ");
scanf("%s",fn);
printf("\nEnter the pattern to be searched: ");
scanf("%s",pat);
fp=fopen(fn,"r");
if(fp==NULL)
{
printf("\nFile does not exist");
}
else
{
while (!feof(fp))
{
fgets(temp,100,fp);
if(strstr(temp,pat))
{
printf("%s",pat);
}
}

}
}

7b.Write a program to generate and print Fibonacci series with the following
requirements:
- Parent program should create a child and distribute the task of generating
Fibonacci no to
its child.
- The code for generating Fibonacci no. should reside in different program.
- Child should write the generated Fibonacci sequence to a shared memory.
- Parent process has to print by retrieving the Fibonacci sequence from the shared
memory.
i) Implement the above using shmget and shmat
Note: Shared object should be removed at the end in the program
Program:

//Parent.c
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int i;
pid_t pid;
int k, n1, n2, n3;
const int SIZE = 4096;
int shmid;
void *ptr;
shmid = shmget((key_t)1122, 4096, 0666 | IPC_CREAT);
ptr = shmat(shmid, NULL, 0666);
if (argc > 1) {
sscanf(argv[1], "%d", &i);
if (i < 1) {
printf("\nError input");
exit(0);
}
} else {
return (0);
}
pid = fork();
if (pid == 0) {
execlp("./fib", "fib", argv[1], NULL);
} else if (pid > 0) {
wait(NULL);
printf("\nPARENT: Child Completed ");
printf("\nParent Printing:");
printf("%s", (char *)ptr);
shmctl(shmid, IPC_RMID, NULL);
}
return (0);
}

//Child.c
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int k = 2, n1, n2, n3;
void *ptr;
int shmid = shmget((key_t)1122, 4096, 0666);
ptr = shmat(shmid, NULL, 0666);
printf("CHILD:\n");
int i = atoi(argv[1]);
n1 = 0;
n2 = 1;
sprintf(ptr, "%d ", n1);
ptr += strlen(ptr);
printf("%d ", n1);
sprintf(ptr, "%d ", n2);
ptr += strlen(ptr);
printf("%d ", n2);
while (k != i) {
n3 = n1 + n2;
sprintf(ptr, "%d ", n3);
printf("%d ", n3);
n1 = n2;
n2 = n3;
ptr += strlen(ptr);
k++;
}
return 0;
}
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-
8a. Write a program to simulate ls command using system calls
Program:
/*C program to simulate ls command using system calls*/
#include<stdio.h>
#include<stdlib.h>
#include<dirent.h>
#include<sys/types.h>
void main(int argc,char *argv[])
{
DIR *dp;
struct dirent *dirp;
if(argc<2)
{
printf("\nKindly pass the directory onto the file");
exit(0);
}
if((dp==opendir(argv[1]))==NULL)
{
printf("\nCannot open the file %s passed as the arument");
exit(0);
}
while ((dirp==readdir(dp))!=NULL)
{
printf("%s\n",dirp->d_name);
}
closedir(dp);
}

8b. Write a program to generate and print Fibonacci series with the following
requirements:
- Parent program should create a child and distribute the task of generating
Fibonacci no to
its child.
- The code for generating Fibonacci no. should reside in different program.
- Child should write the generated Fibonacci sequence to a shared memory.
- Parent process has to print by retrieving the Fibonacci sequence from the shared
memory.
i) Implement the above using shm_open and mmap
Note: Shared object should be removed at the end in the program

Program:

-----------------------------------------------------------------------------------
---------------------------------------------------------------------------------
9a. Write a Shell program to check whether a given number is palindrome or not
#Shell Script to check whether a given number is palindrome or not
#!/bin/bash
echo "Enter the number"
read num
num1=$num
zero=0
while [ $num1 != $zero ]
do
rem=$((num1%10))
rev=$((rev*10))
rev=$((rev+rem))
num1=$((num1/10))
done
if [ $num == $rev ]
then
echo "$num is a palindrome"
else
echo "$num is not a palindrome"
fi

9b. Write a program to generate and print N ODD numbers with the following
requirements:
- Parent program should create a child and distribute the task of generating odd
numbers to
its child.
- The code for generating odd numbers should reside in different program.
- Child should write the generated odd numbers to a shared memory.
- Parent process has to print the odd numbers by retrieving from the shared memory.
i) Implement the above using shmget and shmat
Note: Shared object should be removed at the end in the program

Program:
//Parent.c
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/mman.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int i, k, n1 = 0, n2 = 1, n3;
pid_t pid;
const int SIZE = 4096;
int shmid;
void *ptr;
shmid = shmget((key_t)1122, 4096, 0666 | IPC_CREAT);
ptr = shmat(shmid, NULL, 0666);
if (argc > 1) {
sscanf(argv[1], "%d", &i);
if (i < 1) {
printf("Error input: %d\n", i);
return 0;
}
} else {
return 1;
}
pid = fork();
if (pid == 0) {
execlp("./fib", "fib", argv[1], NULL);
} else if (pid > 0) {
wait(NULL);
printf("\nParent: Child completed\n");
printf("Parent printing: \n");
printf("%s", (char *)ptr);
shmctl(shmid, IPC_RMID, NULL);
}
return 0;
}

//Child.c
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/mman.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

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


int i, j;
void *ptr;
int shmid = shmget((key_t)1122, 4096, 0666);
ptr = shmat(shmid, NULL, 0666);
printf("CHILD:\n");
i = atoi(argv[1]);
printf("\n");
for (int j = 1; j < i; j = j + 2) {
sprintf(ptr, "%d\t", j);
printf("%d\t", j);
}
return 0;
}

-----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
10a. Shell program to simulate a calculator
Program:
#Shell Script to simulate a calculator
#!/bin/bash
echo "Enter the first number"
read n1
echo "Enter the second number"
read n2
echo "Enter the operator"
read op
case $op in
'+')
echo "The sum of $n1 and $n2 is $((n1+n2))"
;;
'/')
echo "The quotient of $n1 and $n2 is $((n1/n2))"
;;
'-')
echo "The difference of $n1 and $n2 is $((n1-n2))"
;;
'*')
echo "The product of $n1 and $n2 is $((n1*n2))"
;;
'%')
echo "The remainder of $n1 and $n2 is $((n1%n2))"
;;
*)
echo "Invalid Opeartor entered"
;;
esac

10b.
-----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
11a. A. Write a program to perform the following tasks using system calls:
i) Parent process should create a child process
ii) Both parent child processes should display their pid and parent’s pid; parent
process
should also its child’s pid
iii) Load a new program into child process
iv) The parent process should terminate after the child process terminate
Program:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/ipc.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
#include<sys/mman.h>
void main()
{
void *psm;
char buf[10];
int shmid;
shmid=shm_open("OS",O_CREAT | O_RDWR,0666);
ftruncate(shmid,1024);
psm=mmap(0,1024,PROT_WRITE,MAP_SHARED,shmid,0);
printf("\nKey/ID/fd of the shared memory: %d",shmid);
printf("\nShared memory is attached at: %d",psm);
printf("\nEnter some data to write shared memory: ");
read(0,buf,10);
sprintf(psm,"%s",buf);
}

#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/ipc.h> //Unix commands
#include<sys/shm.h> //Unix commands
#include<sys/mman.h> //unix commands
#include<sys/stat.h>
#include<unistd.h>
void main()
{
void *psm;
int shmid;
shmid=shm_open("OS",O_RDONLY,0666);
ftruncate(shmid,1024);
psm=mmap(0,1024,PROT_READ,MAP_SHARED,shmid,0);
printf("\nKey/ID/fs of the shared memory: %d",shmid);
printf("\nShared memory for consumer is attached at: %d",psm);
printf("%s",(char *)psm);
printf("\n");
shm_unlink("OS");
}

11b. Write a program that implement solution to Producer-Consumer problem using


mutex and Semaphores
Program:
/*C program to implement producer consumer process*/
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
#define MAX 3
#define BUffer 3
sem_t empty,full;
int in=0,out=0;
pthread_mutex_t mutex;
int buffer[BUffer];
void *producer(void *pro)
{
int item;
for(int i=0;i<MAX;i++)
{
item=rand()%100;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
buffer[in]=item;
printf("\nProducer %d inserted an item %d",(int *)pro,item);
in=(in+1)%BUffer;
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void *consumer(void *cno)
{
for(int i=0;i<BUffer;i++)
{
sem_wait(&full);
pthread_mutex_lock(&mutex);
int item=buffer[out];
printf("\nConsumer %d removed %d",(int *)cno,item);
out=(out+1)%BUffer;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
void main()
{
pthread_t pro[3],con[3];
pthread_mutex_init(&mutex,NULL);
sem_init(&empty,0,BUffer);
sem_init(&full,0,0);
int a[5]={1,2,3,4,5};
for(int i=0;i<3;i++)
pthread_create(&pro[i],NULL,(void *)producer,&a[i]);
for(int i=0;i<3;i++)
pthread_create(&con[i],NULL,(void *)consumer,&a[i]);
for(int i=0;i<3;i++)
pthread_join(pro[i],NULL);
for(int i=0;i<3;i++)
pthread_join(con[i],NULL);
pthread_mutex_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
}

-----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
12a. Write a Shell program to find the largest of three numbers
Program:
#Shell script to find the largest of three numbers
#!/bin/bash
echo "Enter the first number"
read n1
echo "Enter the second number"
read n2
echo "Enter the third number"
read n3
large=$n1
if [ $n2 -gt $large ]
then
large=$n2
fi
if [ $n3 -gt $large ]
then
large=$n3
fi
echo "The largest among $n1,$n2 and $n3 is $large"

12b. Write a program that implement solution to readers writers problem using mutex
and semaphores
Program:
/*C program to implement readers writers problem using Semaphores and Mutex*/
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
sem_t wrt;
pthread_mutex_t mutex;
int count=1,num_reader=0;
void *writer(void *Wno)
{
sem_wait(&wrt);
count*=2;
printf("\nWriter %d is modified the count value to %d",((int *)Wno),count);
sem_post(&wrt);
}
void *reader(void *Rno)
{
pthread_mutex_lock(&mutex);
num_reader++;
if(num_reader==1)
sem_wait(&wrt);
pthread_mutex_unlock(&mutex);
printf("\nReader %d read the count as %d",((int *)Rno),count);
pthread_mutex_lock(&mutex);
num_reader--;
if(num_reader==0)
{
sem_post(&wrt);
}
pthread_mutex_unlock(&mutex);
}
void main()
{
int i;
pthread_t read[10],write[10];
pthread_mutex_init(&mutex,NULL);
sem_init(&wrt,0,1);
int a[10]={1,2,3,4,5,6,7,8,9,10};
for(i=0;i<10;i++)
pthread_create(&read[i],NULL,(void *)reader,(void *)&a[i]);
for(i=0;i<10;i++)
pthread_create(&write[i],NULL,(void *)writer,(void *)&a[i]);
for(i=0;i<10;i++)
pthread_join(read[i],NULL);
for(i=0;i<10;i++)
pthread_join(write[i],NULL);
sem_destroy(&wrt);
}

You might also like