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

OS Lab File

The document contains a series of experiments demonstrating various programming tasks in Shell and C. These tasks include checking if a number is even or odd, swapping integers, calculating factorials, generating Fibonacci series, and implementing process management with system calls. Additionally, it covers CPU scheduling algorithms and synchronization problems like the Producer-Consumer and Dining Philosopher problems using semaphores.

Uploaded by

halaplay385
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)
4 views

OS Lab File

The document contains a series of experiments demonstrating various programming tasks in Shell and C. These tasks include checking if a number is even or odd, swapping integers, calculating factorials, generating Fibonacci series, and implementing process management with system calls. Additionally, it covers CPU scheduling algorithms and synchronization problems like the Producer-Consumer and Dining Philosopher problems using semaphores.

Uploaded by

halaplay385
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
You are on page 1/ 21

EXPERIMENT NO-2

AIM: To Write a Shell program to check the given number is even or odd.
ALGORITHM:
SEPT 1: Start the program.
STEP 2: Read the value of n.
STEP 3: Calculate „r=expr $n%2‟.
STEP 4: If the value of r equals 0 then print the number is even
STEP 5: If the value of r not equal to 0 then print the number is odd.

PROGRAM:
echo "Enter the Number"
read n
r=`expr $n % 2`
if [ $r -eq 0 ]
then
echo "$n is Even number"
else
echo "$n is Odd number"
fi

Output:
EXPERIMENT NO-3
AIM: Write a Shell program to swap the two integers.
ALGORITHM:
SEPT 1: Start the program.
STEP 2: Read the value of a,b.
STEP 3: Calculate the swapping of two values by using a temporary variable temp.
STEP 4: Print the value of a and b.

PROGRAM:
echo "Enter Two Numbers"
read a b
temp=$a
a=$b
b=$temp
echo "after swapping"
echo $a $b

Output:
EXPERIMENT NO-4
Aim: Write a Shell program to find the factorial of a number
ALGORITHM:

SEPT 1: Start the program.


STEP 2: Read the value of n.
STEP 3: Calculate „i=expr $n-1‟.
STEP 4: If the value of i is greater than 1 then calculate „n=expr $n \* $i‟ and „i=expr $i – 1‟
STEP 5: Print the factorial of the given number.

PROGRAM:
echo "Enter a Number"
read n i=`expr $n - 1`
p=1
while [ $i -ge 1 ]
do
n=`expr $n \* $i`
i=`expr $i - 1`
done
echo "The Factorial of the given Number is $n"

Output:
EXPERIMENT NO-5
Aim: write a shell program to generate fibonacci series
Algorithm:
Step1: Define how many terms (n) of the Fibonacci series you want to generate.
Step2: Set first = 0 and second = 1 as the initial two Fibonacci numbers.
Step3:
Print the current Fibonacci number.
Calculate the next number: next = first + second.
Update values: first = second, second = next.
Step4: Repeat until the required n terms are generated.

Program:

echo "Enter the number of terms:"


read n

first=0
second=1

echo "Fibonacci Series:"


for (( i=0; i<n; i++ ))
do
echo -n "$first "
next=$((first + second))
first=$second
second=$next
done

echo

Output:
EXPERIMENT NO-6
Aim: Write a C program using the following system calls (fork, exec).

Algorithm:

1. Initialize the program and define pid_t variable for process management.
2. Invoke fork() to create a child process.
o If fork() fails, print an error.
o If fork() succeeds, identify whether the process is child or parent.
3. In the child process:
o Print a message indicating execution inside WSL.
o Call execl() to replace the child process with ls -l.
o Handle errors if exec() fails.
4. In the parent process:
o Print a message indicating process tracking.
o Use wait() to synchronize execution.
o Print completion status.

Program:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
pid_t pid;

// Create a child process


pid = fork();

if (pid < 0) {
// Error handling
perror("Fork failed");
return 1;
}
else if (pid == 0) {
// Child process
printf("Child process running in WSL with PID %d\n", getpid());

// Execute a new process (e.g., listing files in the current directory)


execl("/usr/bin/ls", "ls", "-l", (char *)NULL);

// If exec fails
perror("Exec failed");
return 1;
}
else {
// Parent process
printf("Parent process running in WSL with PID %d, waiting for child process to finish\n",
getpid());

// Wait for child process to complete


wait(NULL);

printf("Child process finished execution\n");


}

return 0;
}

Output:
EXPERIMENT NO-7
Aim: Write a C program using the following system calls (get_pid, exit).

Algorithm:

1. Start
2. Retrieve Process ID
o Use the system call getpid() to obtain the current process's PID.
o Print the process ID.
3. Prepare for termination
o Print a message indicating that the process is exiting.
4. Terminate the process
o Use the system call exit(0) to exit immediately.
5. End

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

int main() {
printf("Process running with PID: %d\n", getpid());

printf("Exiting the process now.\n");


exit(0); // Exiting the process

return 0; // This will never execute due to exit()


}

Output:
EXPERIMENT NO-8
Aim: Write a C program using the I/O system calls (open, read, write, etc).
Program:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

#define BUFFER_SIZE 1024

int main() {
int source_fd, dest_fd;
char buffer[BUFFER_SIZE];
ssize_t bytes_read;

// Open the source file for reading


source_fd = open("input.txt", O_RDONLY);
if (source_fd < 0) {
perror("Error opening input file");
return 1;
}

// Open the destination file for writing (create if doesn't exist)


dest_fd = open("output.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (dest_fd < 0) {
perror("Error opening output file");
close(source_fd);
return 1;
}

// Read data from source file and write to destination file


while ((bytes_read = read(source_fd, buffer, BUFFER_SIZE)) > 0) {
if (write(dest_fd, buffer, bytes_read) < 0) {
perror("Error writing to output file");
close(source_fd);
close(dest_fd);
return 1;
}
}

// Close files
close(source_fd);
close(dest_fd);

printf("File copy operation completed successfully.\n");

return 0;
}
Output:
EXPERIMENT NO- 9

Aim: Write a C program to simulate CPU scheduling algorithms: FCFS, SJF, and Round
Robin

a)FCFS:
Program:

#include <stdio.h>

// Function to calculate waiting time and turnaround time


void findWaitingTime(int processes[], int n, int bt[], int wt[]) {
wt[0] = 0; // First process has no waiting time

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


wt[i] = bt[i - 1] + wt[i - 1];
}
}

void findTurnaroundTime(int processes[], int n, int bt[], int wt[], int tat[]) {
for (int i = 0; i < n; i++) {
tat[i] = bt[i] + wt[i];
}
}

void findAvgTime(int processes[], int n, int bt[]) {


int wt[n], tat[n];
float total_wt = 0, total_tat = 0;

findWaitingTime(processes, n, bt, wt);


findTurnaroundTime(processes, n, bt, wt, tat);

printf("\nFCFS Scheduling:\n\nP BT WT TAT\n");

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


printf("P%d %d %d %d\n", processes[i], bt[i], wt[i], tat[i]);
total_wt += wt[i];
total_tat += tat[i];
}

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


printf("Average Turnaround Time: %.2f\n", total_tat / n);
}

int main() {
int processes[] = {1, 2, 3}; // Process IDs
int n = sizeof(processes) / sizeof(processes[0]);
int bt[] = {5, 8, 6}; // Burst time of processes
printf("FCFS Output\n");
findAvgTime(processes, n, bt);

return 0;
}

Output:

b)SJF:
Program:
#include <stdio.h>

// Function to sort processes by Burst Time (BT)


void sortByBurstTime(int n, int processes[], int bt[]) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (bt[i] > bt[j]) {
// Swap burst time
int temp = bt[i];
bt[i] = bt[j];
bt[j] = temp;

// Swap process IDs


temp = processes[i];
processes[i] = processes[j];
processes[j] = temp;
}
}
}
}

// Function to calculate Waiting Time (WT)


void findWaitingTime(int n, int bt[], int wt[]) {
wt[0] = 0; // First process has no waiting time

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


wt[i] = bt[i - 1] + wt[i - 1];
}
}

// Function to calculate Turnaround Time (TAT)


void findTurnaroundTime(int n, int bt[], int wt[], int tat[]) {
for (int i = 0; i < n; i++) {
tat[i] = bt[i] + wt[i];
}
}

void findAvgTime(int n, int processes[], int bt[]) {


int wt[n], tat[n];
float total_wt = 0, total_tat = 0;

// Sort processes by shortest burst time


sortByBurstTime(n, processes, bt);

findWaitingTime(n, bt, wt);


findTurnaroundTime(n, bt, wt, tat);

printf("\nSJF Scheduling:\n\nP BT WT TAT\n");

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


printf("P%d %d %d %d\n", processes[i], bt[i], wt[i], tat[i]);
total_wt += wt[i];
total_tat += tat[i];
}

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


printf("Average Turnaround Time: %.2f\n", total_tat / n);
}

int main() {
int processes[] = {1, 2, 3}; // Process IDs
int n = sizeof(processes) / sizeof(processes[0]);
int bt[] = {8, 5, 6}; // Burst time of processes (unsorted)

printf("SJF Output\n");
findAvgTime(n, processes, bt);

return 0;
}
Output:

c)Round Robin:
Program:
#include <stdio.h>

// Function to implement Round Robin scheduling


void findWaitingTime(int processes[], int n, int bt[], int quantum, int wt[]) {
int rem_bt[n]; // Remaining burst times
for (int i = 0; i < n; i++)
rem_bt[i] = bt[i];

int t = 0; // Current time

while (1) {
int done = 1;
for (int i = 0; i < n; i++) {
if (rem_bt[i] > 0) {
done = 0;
if (rem_bt[i] > quantum) {
t += quantum;
rem_bt[i] -= quantum;
} else {
t += rem_bt[i];
wt[i] = t - bt[i];
rem_bt[i] = 0;
}
}
}
if (done) break;
}
}

// Function to calculate Turnaround Time


void findTurnaroundTime(int n, int bt[], int wt[], int tat[]) {
for (int i = 0; i < n; i++)
tat[i] = bt[i] + wt[i];
}
void findAvgTime(int processes[], int n, int bt[], int quantum) {
int wt[n], tat[n];
float total_wt = 0, total_tat = 0;

findWaitingTime(processes, n, bt, quantum, wt);


findTurnaroundTime(n, bt, wt, tat);

printf("\nRound Robin Scheduling:\n\nP BT WT TAT\n");

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


printf("P%d %d %d %d\n", processes[i], bt[i], wt[i], tat[i]);
total_wt += wt[i];
total_tat += tat[i];
}

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


printf("Average Turnaround Time: %.2f\n", total_tat / n);
}

int main() {
int processes[] = {1, 2, 3}; // Process IDs
int n = sizeof(processes) / sizeof(processes[0]);
int bt[] = {5, 8, 6}; // Burst time of processes
int quantum = 3; // Time Quantum

printf("Round Robin Output\n");


findAvgTime(processes, n, bt, quantum);

return 0;
}

Output:
EXPERIMENT NO-10
Aim: Implement the Producer-Consumer problem using semaphores.
Program:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

#define BUFFER_SIZE 5 // Size of buffer

int buffer[BUFFER_SIZE];
int count = 0; // Number of items in buffer

sem_t empty, full; // Semaphores for synchronization


pthread_mutex_t mutex; // Mutex for critical section

void *producer(void *arg) {


for (int i = 1; i <= 10; i++) {
sem_wait(&empty); // Wait if buffer is full
pthread_mutex_lock(&mutex);

buffer[count++] = i;
printf("Producer produced: %d\n", i);

pthread_mutex_unlock(&mutex);
sem_post(&full); // Signal consumer
sleep(1);
}
return NULL;
}

void *consumer(void *arg) {


for (int i = 1; i <= 10; i++) {
sem_wait(&full); // Wait if buffer is empty
pthread_mutex_lock(&mutex);

int item = buffer[--count];


printf("Consumer consumed: %d\n", item);

pthread_mutex_unlock(&mutex);
sem_post(&empty); // Signal producer
sleep(2);
}
return NULL;
}

int main() {
pthread_t prod, cons;
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex, NULL);

pthread_create(&prod, NULL, producer, NULL);


pthread_create(&cons, NULL, consumer, NULL);

pthread_join(prod, NULL);
pthread_join(cons, NULL);

sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);

return 0;
}

Output:
EXPERIMENT NO-11
Aim: Implement the Dining Philospher problem using semaphores.
Program:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

#define N 5 // Number of philosophers

sem_t forks[N]; // Semaphores representing forks


sem_t mutex; // Semaphore to prevent deadlock

void *philosopher(void *arg) {


int id = *(int *)arg;

while (1) {
printf("Philosopher %d is thinking\n", id);
sleep(1);

// Pick up forks
sem_wait(&mutex); // Prevent deadlock
sem_wait(&forks[id]); // Pick left fork
sem_wait(&forks[(id + 1) % N]); // Pick right fork
sem_post(&mutex);

printf("Philosopher %d is eating\n", id);


sleep(2);

// Put down forks


sem_post(&forks[id]); // Release left fork
sem_post(&forks[(id + 1) % N]); // Release right fork

printf("Philosopher %d finished eating\n", id);


sleep(1);
}
}

int main() {
pthread_t philosophers[N];
int ids[N];

sem_init(&mutex, 0, 1);
for (int i = 0; i < N; i++)
sem_init(&forks[i], 0, 1);

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


ids[i] = i;
pthread_create(&philosophers[i], NULL, philosopher, &ids[i]);
}

for (int i = 0; i < N; i++)


pthread_join(philosophers[i], NULL);

for (int i = 0; i < N; i++)


sem_destroy(&forks[i]);
sem_destroy(&mutex);

return 0;
}

Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy