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

Os Lab Bca

The document contains multiple C programs demonstrating process and thread creation, termination, inter-process communication (IPC) using named pipes, and various CPU scheduling algorithms including FCFS, SJF, SRTF, and RR. Each program includes necessary structures, functions for calculating waiting and turnaround times, and outputs relevant information to the console. The document serves as a comprehensive guide for implementing these concepts in C programming.

Uploaded by

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

Os Lab Bca

The document contains multiple C programs demonstrating process and thread creation, termination, inter-process communication (IPC) using named pipes, and various CPU scheduling algorithms including FCFS, SJF, SRTF, and RR. Each program includes necessary structures, functions for calculating waiting and turnaround times, and outputs relevant information to the console. The document serves as a comprehensive guide for implementing these concepts in C programming.

Uploaded by

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

1.

Write a C program for implementing process creation

and termination.

#include <windows.h>

#include <stdio.h>

int main() {

STARTUPINFO si;

PROCESS_INFORMATION pi;

// Initialize memory for the structures

ZeroMemory(&si, sizeof(si));

si.cb = sizeof(si);

ZeroMemory(&pi, sizeof(pi));

// Command to create the process (example: notepad.exe)

char command[] = "notepad.exe";

// Create a new process

if (!CreateProcess(NULL, // Application name

command, // Command line

NULL, // Process handle not inheritable

NULL, // Thread handle not inheritable

FALSE, // Set handle inheritance to FALSE

0, // No creation flags

NULL, // Use parent's environment block

NULL, // Use parent's starting directory

&si, // Pointer to STARTUPINFO structure

&pi)) // Pointer to PROCESS_INFORMATION structure

{
printf("Process creation failed (%d).\n", GetLastError());

return 1;

printf("Process created. PID: %lu\n", pi.dwProcessId);

// Wait for 5 seconds before terminating the process

Sleep(5000);

// Terminate the process

if (!TerminateProcess(pi.hProcess, 0)) {

printf("Process termination failed (%d).\n", GetLastError());

} else {

printf("Process terminated successfully.\n");

// Close process and thread handles

CloseHandle(pi.hProcess);

CloseHandle(pi.hThread);

return 0;

2. Write a C program for implementing thread creation and

termination.

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>
// Function to be executed by each thread

void* threadFunction(void* arg) {

int threadNum = *((int*)arg);

printf("Thread %d is running...\n", threadNum);

// Simulate some work with a sleep

sleep(1);

printf("Thread %d has finished execution.\n", threadNum);

pthread_exit(NULL);

int main() {

pthread_t thread1, thread2;

int threadNum1 = 1, threadNum2 = 2;

int status;

// Create thread 1

status = pthread_create(&thread1, NULL, threadFunction, (void*)&threadNum1);

if (status != 0) {

printf("Failed to create thread 1\n");

exit(EXIT_FAILURE);

// Create thread 2

status = pthread_create(&thread2, NULL, threadFunction, (void*)&threadNum2);

if (status != 0) {

printf("Failed to create thread 2\n");

exit(EXIT_FAILURE);

}
// Wait for thread 1 to finish

pthread_join(thread1, NULL);

// Wait for thread 2 to finish

pthread_join(thread2, NULL);

printf("Both threads have terminated.\n");

return 0;

3. Simulate IPC techniques using C program.

Client

#include <windows.h>

#include <stdio.h>

#define PIPE_NAME "\\\\.\\pipe\\MyNamedPipe"

#define BUFFER_SIZE 1024

int main() {

HANDLE hPipe;

char buffer[BUFFER_SIZE];

DWORD bytesRead, bytesWritten;

// Wait for the server to create the pipe

hPipe = CreateFile(

PIPE_NAME, // Pipe name

GENERIC_READ | // Read access

GENERIC_WRITE, // Write access


0, // No sharing

NULL, // Default security attributes

OPEN_EXISTING, // Opens existing pipe

0, // Default attributes

NULL // No template file

);

if (hPipe == INVALID_HANDLE_VALUE) {

printf("Failed to connect to named pipe. Error: %d\n", GetLastError());

return 1;

printf("Connected to server!\n");

// Send data to the server

const char* message = "Hello from client!";

WriteFile(hPipe, message, strlen(message) + 1, &bytesWritten, NULL);

// Read the server's response

if (ReadFile(hPipe, buffer, BUFFER_SIZE, &bytesRead, NULL)) {

printf("Received from server: %s\n", buffer);

} else {

printf("Failed to read from pipe. Error: %d\n", GetLastError());

// Close the pipe

CloseHandle(hPipe);

printf("Client finished communication.\n");


return 0;

Server

#include <windows.h>

#include <stdio.h>

#define PIPE_NAME "\\\\.\\pipe\\MyNamedPipe"

#define BUFFER_SIZE 1024

int main() {

HANDLE hPipe;

char buffer[BUFFER_SIZE];

DWORD bytesRead, bytesWritten;

// Create a named pipe

hPipe = CreateNamedPipe(

PIPE_NAME, // Pipe name

PIPE_ACCESS_DUPLEX, // Read/Write access

PIPE_TYPE_MESSAGE | // Message-type pipe

PIPE_READMODE_MESSAGE | // Message-read mode

PIPE_WAIT, // Blocking mode

1, // Number of instances

BUFFER_SIZE, // Output buffer size

BUFFER_SIZE, // Input buffer size

0, // Default timeout

NULL // Default security attributes

);

if (hPipe == INVALID_HANDLE_VALUE) {
printf("Failed to create named pipe. Error: %d\n", GetLastError());

return 1;

printf("Waiting for a client to connect...\n");

// Wait for a client to connect

BOOL connected = ConnectNamedPipe(hPipe, NULL) ? TRUE : (GetLastError() ==


ERROR_PIPE_CONNECTED);

if (!connected) {

printf("Failed to connect to client. Error: %d\n", GetLastError());

CloseHandle(hPipe);

return 1;

printf("Client connected!\n");

// Read data from the pipe

if (ReadFile(hPipe, buffer, BUFFER_SIZE, &bytesRead, NULL)) {

printf("Received from client: %s\n", buffer);

} else {

printf("Failed to read from pipe. Error: %d\n", GetLastError());

// Send a response back to the client

const char* response = "Hello from server!";

WriteFile(hPipe, response, strlen(response) + 1, &bytesWritten, NULL);

// Close the pipe


CloseHandle(hPipe);

printf("Server finished communication.\n");

return 0;

4. Write a C program for Implementing Process Scheduling Algorithm. Also compute TAT and WT time

of each algorithm.

a. FCFS (First Come First Serve)

#include <stdio.h>

struct Process {

int pid; // Process ID

int burstTime; // Burst Time

int waitingTime; // Waiting Time

int turnAroundTime; // Turnaround Time

};

void calculateWaitingTime(struct Process p[], int n) {

p[0].waitingTime = 0; // First process has 0 waiting time

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

p[i].waitingTime = p[i-1].waitingTime + p[i-1].burstTime;

void calculateTurnAroundTime(struct Process p[], int n) {

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

p[i].turnAroundTime = p[i].waitingTime + p[i].burstTime;


}

void printSchedulingInfo(struct Process p[], int n) {

printf("\nProcess ID\tBurst Time\tWaiting Time\tTurnaround Time\n");

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

printf("%d\t\t%d\t\t%d\t\t%d\n", p[i].pid, p[i].burstTime, p[i].waitingTime, p[i].turnAroundTime);

void calculateAverageTimes(struct Process p[], int n) {

float totalWaitingTime = 0, totalTurnAroundTime = 0;

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

totalWaitingTime += p[i].waitingTime;

totalTurnAroundTime += p[i].turnAroundTime;

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

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

int main() {

int n;

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

scanf("%d", &n);

struct Process p[n];


// Input burst times for each process

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

p[i].pid = i + 1;

printf("Enter burst time for process %d: ", i + 1);

scanf("%d", &p[i].burstTime);

// Calculate waiting time and turnaround time for each process

calculateWaitingTime(p, n);

calculateTurnAroundTime(p, n);

// Print process scheduling information

printSchedulingInfo(p, n);

// Calculate and print average waiting time and turnaround time

calculateAverageTimes(p, n);

return 0;

b. SJF (Shortest Job First)

#include <stdio.h>

// Structure to represent a process

struct Process {

int id; // Process ID

int burstTime; // Burst time (execution time) of the process


int waitTime; // Waiting time of the process

int turnAroundTime; // Turnaround time of the process

};

// Function to swap two processes

void swap(struct Process *a, struct Process *b) {

struct Process temp = *a;

*a = *b;

*b = temp;

// Function to sort processes by burst time using bubble sort

void sortByBurstTime(struct Process proc[], int n) {

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

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

if (proc[j].burstTime > proc[j + 1].burstTime) {

swap(&proc[j], &proc[j + 1]);

// Function to calculate waiting and turnaround times

void calculateTimes(struct Process proc[], int n) {

proc[0].waitTime = 0; // First process doesn't wait

proc[0].turnAroundTime = proc[0].burstTime;

// Calculate waiting time and turnaround time for all processes

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


proc[i].waitTime = proc[i - 1].waitTime + proc[i - 1].burstTime;

proc[i].turnAroundTime = proc[i].waitTime + proc[i].burstTime;

// Function to display process details

void displayProcesses(struct Process proc[], int n) {

float totalWaitTime = 0, totalTurnAroundTime = 0;

printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");

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

totalWaitTime += proc[i].waitTime;

totalTurnAroundTime += proc[i].turnAroundTime;

printf("P%d\t%d\t\t%d\t\t%d\n", proc[i].id, proc[i].burstTime, proc[i].waitTime,


proc[i].turnAroundTime);

// Display average waiting time and turnaround time

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

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

int main() {

int n;

// Input number of processes

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

scanf("%d", &n);
struct Process proc[n];

// Input burst time for each process

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

proc[i].id = i + 1; // Process ID

printf("Enter burst time for Process P%d: ", proc[i].id);

scanf("%d", &proc[i].burstTime);

// Sort processes by burst time (Shortest Job First)

sortByBurstTime(proc, n);

// Calculate waiting and turnaround times

calculateTimes(proc, n);

// Display process details

displayProcesses(proc, n);

return 0;

c. SRTF (Shortest Remaining Time First)

#include <stdio.h>

// Structure to represent a process

struct Process {

int id; // Process ID

int burstTime; // Burst time (execution time) of the process


int waitTime; // Waiting time of the process

int turnAroundTime; // Turnaround time of the process

};

// Function to swap two processes

void swap(struct Process *a, struct Process *b) {

struct Process temp = *a;

*a = *b;

*b = temp;

// Function to sort processes by burst time using bubble sort

void sortByBurstTime(struct Process proc[], int n) {

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

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

if (proc[j].burstTime > proc[j + 1].burstTime) {

swap(&proc[j], &proc[j + 1]);

// Function to calculate waiting and turnaround times

void calculateTimes(struct Process proc[], int n) {

proc[0].waitTime = 0; // First process doesn't wait

proc[0].turnAroundTime = proc[0].burstTime;

// Calculate waiting time and turnaround time for all processes

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


proc[i].waitTime = proc[i - 1].waitTime + proc[i - 1].burstTime;

proc[i].turnAroundTime = proc[i].waitTime + proc[i].burstTime;

// Function to display process details

void displayProcesses(struct Process proc[], int n) {

float totalWaitTime = 0, totalTurnAroundTime = 0;

printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");

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

totalWaitTime += proc[i].waitTime;

totalTurnAroundTime += proc[i].turnAroundTime;

printf("P%d\t%d\t\t%d\t\t%d\n", proc[i].id, proc[i].burstTime, proc[i].waitTime,


proc[i].turnAroundTime);

// Display average waiting time and turnaround time

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

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

int main() {

int n;

// Input number of processes

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

scanf("%d", &n);
struct Process proc[n];

// Input burst time for each process

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

proc[i].id = i + 1; // Process ID

printf("Enter burst time for Process P%d: ", proc[i].id);

scanf("%d", &proc[i].burstTime);

// Sort processes by burst time (Shortest Job First)

sortByBurstTime(proc, n);

// Calculate waiting and turnaround times

calculateTimes(proc, n);

// Display process details

displayProcesses(proc, n);

return 0;

d. RR (Round-Robbin CPU Scheduling Algorithm).

#include <stdio.h>

void findWaitingTimeRR(int processes[], int n, int bt[], int wt[], int quantum) {

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; // There is a pending process

if (rem_bt[i] > quantum) {

t += quantum;

rem_bt[i] -= quantum;

} else {

t += rem_bt[i];

wt[i] = t - bt[i]; // Waiting time is current time minus burst time

rem_bt[i] = 0;

if (done == 1)

break;

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 findAverageTimeRR(int processes[], int n, int bt[], int quantum) {

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

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

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

printf("Processes Burst Time Waiting Time Turn-Around Time\n");

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

total_wt += wt[i];

total_tat += tat[i];

printf(" %d ", i + 1);

printf(" %d ", bt[i]);

printf(" %d ", wt[i]);

printf(" %d\n", tat[i]);

printf("\nAverage waiting time = %.2f", (float)total_wt / (float)n);

printf("\nAverage turn-around time = %.2f\n", (float)total_tat / (float)n);

int main() {

int n, quantum;

printf("Enter number of processes: ");

scanf("%d", &n);
int processes[n], burst_time[n];

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

processes[i] = i + 1;

printf("Enter burst time for process %d: ", i + 1);

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

printf("Enter time quantum: ");

scanf("%d", &quantum);

findAverageTimeRR(processes, n, burst_time, quantum);

return 0;

e. Priority Scheduling

#include <stdio.h>

void findWaitingTimePriority(int processes[], int n, int bt[], int wt[], int priority[]) {

int completed = 0, currentTime = 0, i;

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

wt[i] = 0; // Initialize all waiting times to 0

while (completed != n) {

int idx = -1;

int highestPriority = 9999; // Arbitrarily large value


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

if (bt[i] > 0 && priority[i] < highestPriority) {

highestPriority = priority[i];

idx = i;

currentTime += bt[idx];

wt[idx] = currentTime - bt[idx]; // Calculate waiting time

bt[idx] = 0; // Mark as completed

completed++;

void findTurnAroundTimePriority(int processes[], int n, int bt[], int wt[], int tat[]) {

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

tat[i] = bt[i] + wt[i];

void findAverageTimePriority(int processes[], int n, int bt[], int priority[]) {

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

findWaitingTimePriority(processes, n, bt, wt, priority);

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

printf("Processes Burst Time Waiting Time Turn-Around Time\n");

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

total_wt += wt[i];
total_tat += tat[i];

printf(" %d ", processes[i]);

printf(" %d ", bt[i]);

printf(" %d ", wt[i]);

printf(" %d\n", tat[i]);

printf("\nAverage waiting time = %.2f", (float)total_wt / (float)n);

printf("\nAverage turn-around time = %.2f\n", (float)total_tat / (float)n);

int main() {

int n;

printf("Enter number of processes: ");

scanf("%d", &n);

int processes[n], burst_time[n], priority[n];

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

processes[i] = i + 1;

printf("Enter burst time for process %d: ", i + 1);

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

printf("Enter priority for process %d: ", i + 1);

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

findAverageTimePriority(processes, n, burst_time, priority);


return 0;

5. Implement Bounded Buffer Problem Using C

Programming.

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

#include <semaphore.h>

#define BUFFER_SIZE 5 // Size of the buffer

int buffer[BUFFER_SIZE]; // Buffer array

int in = 0; // Index to produce an item

int out = 0; // Index to consume an item

sem_t empty; // Semaphore to track empty slots in the buffer

sem_t full; // Semaphore to track full slots in the buffer

pthread_mutex_t mutex; // Mutex to protect shared data (critical section)

// Producer function

void *producer(void *param) {

int item;

for (int i = 0; i < 4; i++) { // Produces 4 items

item = rand() % 100; // Produce a random item

sem_wait(&empty); // Wait for an empty slot in the buffer

pthread_mutex_lock(&mutex); // Enter critical section


// Add the item to the buffer

buffer[in] = item;

printf("Producer produced: %d\n", item);

in = (in + 1) % BUFFER_SIZE; // Circular increment

pthread_mutex_unlock(&mutex); // Exit critical section

sem_post(&full); // Signal that a full slot is available

sleep(1); // Simulate the time taken to produce

pthread_exit(0);

// Consumer function

void *consumer(void *param) {

int item;

for (int i = 0; i < 4; i++) { // Consumes 4 items

sem_wait(&full); // Wait for a full slot in the buffer

pthread_mutex_lock(&mutex); // Enter critical section

// Remove the item from the buffer

item = buffer[out];

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

out = (out + 1) % BUFFER_SIZE; // Circular increment

pthread_mutex_unlock(&mutex); // Exit critical section

sem_post(&empty); // Signal that an empty slot is available


sleep(1); // Simulate the time taken to consume

pthread_exit(0);

int main() {

pthread_t tid1, tid2; // Thread identifiers

pthread_attr_t attr; // Thread attributes

// Initialize the semaphores

sem_init(&empty, 0, BUFFER_SIZE); // Initially, the buffer is empty

sem_init(&full, 0, 0); // Initially, no full slots

pthread_mutex_init(&mutex, NULL); // Initialize mutex

// Initialize thread attributes

pthread_attr_init(&attr);

// Create the producer and consumer threads

pthread_create(&tid1, &attr, producer, NULL);

pthread_create(&tid2, &attr, consumer, NULL);

// Wait for the threads to finish

pthread_join(tid1, NULL);

pthread_join(tid2, NULL);

// Clean up

sem_destroy(&empty);

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

return 0;

You might also like