0% found this document useful (0 votes)
9 views39 pages

Linux Commands and Address Book Program

The document contains multiple C programming assignments, including a Linux commands menu, an address book management system, and sorting algorithms using bubble sort and selection sort. It also includes a preemptive Shortest Job First (SJF) scheduling algorithm implementation. Each part of the assignment demonstrates different programming concepts and functionalities.

Uploaded by

bhushanpat31
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)
9 views39 pages

Linux Commands and Address Book Program

The document contains multiple C programming assignments, including a Linux commands menu, an address book management system, and sorting algorithms using bubble sort and selection sort. It also includes a preemptive Shortest Job First (SJF) scheduling algorithm implementation. Each part of the assignment demonstrates different programming concepts and functionalities.

Uploaded by

bhushanpat31
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

Assignment No 1

Part A

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
int choice;
char input[100];

while (1) {
printf("\n===== Linux Commands Menu =====\n");
printf("1. echo\n");
printf("2. ls\n");
printf("3. read (input from user)\n");
printf("4. cat (display file)\n");
printf("5. touch (create file)\n");
printf("6. test (check file existence)\n");
printf("7. for loop example\n");
printf("8. arithmetic comparison\n");
printf("9. conditional loop (while)\n");
printf("10. grep (search in file)\n");
printf("11. sed (replace text in file)\n");
printf("12. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
getchar(); // clear buffer

switch (choice) {
case 1:
printf("Enter text to echo: ");
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = '\0';
char cmd1[200];
sprintf(cmd1, "echo %s", input);
system(cmd1);
break;

case 2:
system("ls -l");
break;
case 3:
printf("Simulating 'read': Enter your name: ");
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = '\0';
printf("You entered: %s\n", input);
break;

case 4:
printf("Enter filename to display: ");
scanf("%s", input);
char cmd4[200];
sprintf(cmd4, "cat %s", input);
system(cmd4);
break;

case 5:
printf("Enter filename to create: ");
scanf("%s", input);
char cmd5[200];
sprintf(cmd5, "touch %s", input);
system(cmd5);
printf("File created.\n");
break;

case 6:
printf("Enter filename to check: ");
scanf("%s", input);
char cmd6[200];
sprintf(cmd6, "test -f %s && echo 'File exists' || echo 'File not found'",
input);
system(cmd6);
break;

case 7:
printf("For loop from 1 to 5:\n");
system("for i in 1 2 3 4 5; do echo $i; done");
break;

case 8:
printf("Arithmetic Comparison Example: 5 > 3 ?\n");
system("test 5 -gt 3 && echo 'Yes, 5 is greater than 3'");
break;
case 9:
printf("While loop example (prints 1 to 5):\n");
system("i=1; while [ $i -le 5 ]; do echo $i; i=$((i+1)); done");
break;

case 10:
printf("Enter keyword to search in 'HelloWorld.c': ");
scanf("%s", input);
char cmd10[200];
sprintf(cmd10, "grep %s HelloWorld.c", input);
system(cmd10);
break;

case 11:
printf("Replacing 'old' with 'new' in HelloWorld.c\n");
system("sed 's/old/new/g' HelloWorld.c");
break;

case 12:
exit(0);

default:
printf("Invalid choice!\n");
}
}
return 0;
}
Assignment No 1
Part B

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define FILENAME "[Link]"

struct Contact {
int id;
char name[50];
char phone[15];
char email[50];
};

// Function prototypes
void createAddressBook();
void viewAddressBook();
void insertRecord();
void deleteRecord();
void modifyRecord();

int main() {
int choice;
while (1) {
printf("\n===== Address Book =====\n");
printf("1. Create Address Book\n");
printf("2. View Address Book\n");
printf("3. Insert a Record\n");
printf("4. Delete a Record\n");
printf("5. Modify a Record\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1: createAddressBook(); break;
case 2: viewAddressBook(); break;
case 3: insertRecord(); break;
case 4: deleteRecord(); break;
case 5: modifyRecord(); break;
case 6: exit(0);
default: printf("Invalid choice! Try again.\n");
}
}
return 0;
}

// Create address book (overwrite file)


void createAddressBook() {
FILE *fp = fopen(FILENAME, "wb");
if (!fp) {
printf("Error creating file!\n");
return;
}
printf("Address book created successfully (existing data cleared).\n");
fclose(fp);
}

// View address book


void viewAddressBook() {
FILE *fp = fopen(FILENAME, "rb");
if (!fp) {
printf("Error opening file!\n");
return;
}

struct Contact c;
printf("\n--- Address Book Records ---\n");
while (fread(&c, sizeof(c), 1, fp)) {
printf("ID: %d\nName: %s\nPhone: %s\nEmail: %s\n\n",
[Link], [Link], [Link], [Link]);
}
fclose(fp);
}

// Insert new record


void insertRecord() {
FILE *fp = fopen(FILENAME, "ab");
if (!fp) {
printf("Error opening file!\n");
return;
}
struct Contact c;
printf("Enter ID: ");
scanf("%d", &[Link]);
getchar(); // clear buffer
printf("Enter Name: ");
fgets([Link], sizeof([Link]), stdin);
[Link][strcspn([Link], "\n")] = '\0';
printf("Enter Phone: ");
fgets([Link], sizeof([Link]), stdin);
[Link][strcspn([Link], "\n")] = '\0';
printf("Enter Email: ");
fgets([Link], sizeof([Link]), stdin);
[Link][strcspn([Link], "\n")] = '\0';

fwrite(&c, sizeof(c), 1, fp);


printf("Record inserted successfully!\n");
fclose(fp);
}

// Delete a record by ID
void deleteRecord() {
FILE *fp = fopen(FILENAME, "rb");
if (!fp) {
printf("Error opening file!\n");
return;
}
FILE *temp = fopen("[Link]", "wb");
if (!temp) {
printf("Error creating temp file!\n");
fclose(fp);
return;
}

int id, found = 0;


printf("Enter ID to delete: ");
scanf("%d", &id);

struct Contact c;
while (fread(&c, sizeof(c), 1, fp)) {
if ([Link] != id) {
fwrite(&c, sizeof(c), 1, temp);
} else {
found = 1;
}
}

fclose(fp);
fclose(temp);

remove(FILENAME);
rename("[Link]", FILENAME);

if (found) printf("Record deleted successfully!\n");


else printf("Record not found!\n");
}

// Modify a record by ID
void modifyRecord() {
FILE *fp = fopen(FILENAME, "rb+");
if (!fp) {
printf("Error opening file!\n");
return;
}

int id, found = 0;


printf("Enter ID to modify: ");
scanf("%d", &id);
getchar();

struct Contact c;
while (fread(&c, sizeof(c), 1, fp)) {
if ([Link] == id) {
found = 1;
printf("Enter new Name: ");
fgets([Link], sizeof([Link]), stdin);
[Link][strcspn([Link], "\n")] = '\0';
printf("Enter new Phone: ");
fgets([Link], sizeof([Link]), stdin);
[Link][strcspn([Link], "\n")] = '\0';
printf("Enter new Email: ");
fgets([Link], sizeof([Link]), stdin);
[Link][strcspn([Link], "\n")] = '\0';

fseek(fp, -sizeof(c), SEEK_CUR);


fwrite(&c, sizeof(c), 1, fp);
printf("Record modified successfully!\n");
break;
}
}

if (!found) printf("Record not found!\n");


fclose(fp);
}
Assignment No 2
Part A

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>

// Bubble Sort (Parent)


void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1]) {
temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp;
}
}

// Selection Sort (Child)


void selectionSort(int arr[], int n) {
int i, j, min, temp;
for (i = 0; i < n-1; i++) {
min = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min]) min = j;
temp = arr[min]; arr[min] = arr[i]; arr[i] = temp;
}
}

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


// Child process logic
if (argc > 1 && strcmp(argv[1], "child") == 0) {
int n = argc - 2;
int arr[n];
for (int i = 0; i < n; i++)
arr[i] = atoi(argv[i+2]);

printf("\n[Child] PID = %lu, Parent Thread ID = %lu\n", GetCurrentProcessId(),


GetCurrentThreadId());
printf("[Child] Sorting using Selection Sort...\n");

selectionSort(arr, n);
printf("[Child] Sorted array: ");
for (int i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n");
return 0;
}

// Parent process logic


int n, i;
printf("Enter number of integers: ");
scanf("%d", &n);

int arr[n];
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);

// Get full path of the current executable


char exePath[MAX_PATH];
GetModuleFileName(NULL, exePath, MAX_PATH);

// Build command line for child


char cmdLine[1024];
sprintf(cmdLine, "\"%s\" child", exePath);
for (i = 0; i < n; i++) {
char buffer[20];
sprintf(buffer, " %d", arr[i]);
strcat(cmdLine, buffer);
}

// Launch child process


STARTUPINFO si = { sizeof(si) };
PROCESS_INFORMATION pi;

if (!CreateProcess(NULL, cmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {


printf("Failed to create child process. Error: %lu\n", GetLastError());
return 1;
}

printf("\n[Parent] PID = %lu\n", GetCurrentProcessId());


printf("[Parent] Sorting using Bubble Sort...\n");

bubbleSort(arr, n);
printf("[Parent] Sorted array: ");
for (i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n");

// Wait for child to finish


WaitForSingleObject([Link], INFINITE);
CloseHandle([Link]);
CloseHandle([Link]);

printf("[Parent] Child completed. Exiting parent.\n");


return 0;
}
Assignment No 2
Part B

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <string.h>

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}

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


if (argc == 1) {
// ----------------- Parent Process -----------------
int n;
printf("Enter number of elements: ");
scanf("%d", &n);

int arr[n];
printf("Enter elements: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

bubbleSort(arr, n);

printf("\nParent sorted array: ");


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");

// Get full path of current executable


char exePath[MAX_PATH];
GetModuleFileName(NULL, exePath, MAX_PATH);

// Prepare command line for child


char cmdLine[2048] = "\"";
strcat(cmdLine, exePath);
strcat(cmdLine, "\"");

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


char num[20];
sprintf(num, " %d", arr[i]);
strcat(cmdLine, num);
}

// Create child process


STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
[Link] = sizeof(si);
ZeroMemory(&pi, sizeof(pi));

if (!CreateProcess(NULL, cmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {


printf("CreateProcess failed (%d)\n", GetLastError());
return 1;
}

printf("Parent PID: %d, Child PID: %d\n", GetCurrentProcessId(), [Link]);

// Wait for child to finish


WaitForSingleObject([Link], INFINITE);

CloseHandle([Link]);
CloseHandle([Link]);

printf("Parent: Child finished.\n");


}
else {
// ----------------- Child Process -----------------
int n = argc - 1;
int arr[n];

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


arr[i] = atoi(argv[i+1]);
}
printf("\nChild (PID %d) received array: ", GetCurrentProcessId());
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);

printf("\nChild printing in reverse: ");


for (int i = n-1; i >= 0; i--)
printf("%d ", arr[i]);
printf("\n");

printf("Child sleeping for 5 seconds to simulate orphan/zombie scenario...\n");


Sleep(5000); // Simulate time for orphan/zombie demo
}

return 0;
}
Assignment No 3

#include <stdio.h>
#include <limits.h>

struct Process {
int pid; // Process ID
int at; // Arrival Time
int bt; // Burst Time
int rt; // Remaining Time
int ct; // Completion Time
int tat; // Turnaround Time
int wt; // Waiting Time
};

// ------------------ SJF Preemptive ------------------


void SJF_Preemptive(struct Process p[], int n) {
int complete = 0, t = 0, min_rt, shortest = -1;
for (int i = 0; i < n; i++) p[i].rt = p[i].bt;

while (complete != n) {
min_rt = INT_MAX;
shortest = -1;

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


if (p[j].at <= t && p[j].rt > 0 && p[j].rt < min_rt) {
min_rt = p[j].rt;
shortest = j;
}
}

if (shortest == -1) { // No process available


t++;
continue;
}

p[shortest].rt--; // Execute 1 unit


if (p[shortest].rt == 0) {
complete++;
p[shortest].ct = t + 1;
p[shortest].tat = p[shortest].ct - p[shortest].at;
p[shortest].wt = p[shortest].tat - p[shortest].bt;
}
t++;
}

printf("\n--- Shortest Job First (Preemptive) ---\n");


printf("PID\tAT\tBT\tCT\tTAT\tWT\n");
float avg_tat = 0, avg_wt = 0;
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].tat, p[i].wt);
avg_tat += p[i].tat;
avg_wt += p[i].wt;
}
printf("Average TAT = %.2f\n", avg_tat / n);
printf("Average WT = %.2f\n", avg_wt / n);
}

// ------------------ Round Robin ------------------


void RoundRobin(struct Process p[], int n, int tq) {
int complete = 0, t = 0, flag;
for (int i = 0; i < n; i++) p[i].rt = p[i].bt;

while (complete != n) {
flag = 0;
for (int i = 0; i < n; i++) {
if (p[i].at <= t && p[i].rt > 0) {
flag = 1;
if (p[i].rt > tq) {
t += tq;
p[i].rt -= tq;
} else {
t += p[i].rt;
p[i].ct = t;
p[i].tat = p[i].ct - p[i].at;
p[i].wt = p[i].tat - p[i].bt;
p[i].rt = 0;
complete++;
}
}
}
if (!flag) t++; // CPU idle
}

printf("\n--- Round Robin (TQ = %d) ---\n", tq);


printf("PID\tAT\tBT\tCT\tTAT\tWT\n");
float avg_tat = 0, avg_wt = 0;
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].tat, p[i].wt);
avg_tat += p[i].tat;
avg_wt += p[i].wt;
}
printf("Average TAT = %.2f\n", avg_tat / n);
printf("Average WT = %.2f\n", avg_wt / n);
}

// ------------------ Main ------------------


int main() {
int n, tq;
printf("Enter number of processes: ");
scanf("%d", &n);

struct Process p[n], copy[n];


for (int i = 0; i < n; i++) {
p[i].pid = i + 1;
printf("Enter Arrival Time & Burst Time for P%d: ", i + 1);
scanf("%d %d", &p[i].at, &p[i].bt);
copy[i] = p[i]; // Backup for RR
}

// Run SJF (Preemptive)


SJF_Preemptive(p, n);

printf("\nEnter Time Quantum for Round Robin: ");


scanf("%d", &tq);

// Run Round Robin


RoundRobin(copy, n, tq);

return 0;
}
Assignment No 4
Part A

#include <stdio.h>
#include <windows.h>

#define BUFFER_SIZE 5

int buffer[BUFFER_SIZE];
int in = 0, out = 0;

// Synchronization objects
HANDLE mutex; // For mutual exclusion
HANDLE emptySemaphore; // Counts empty slots
HANDLE fullSemaphore; // Counts full slots

// Producer function
DWORD WINAPI Producer(LPVOID lpParam) {
int item;
for (int i = 1; i <= 10; i++) {
item = i;

// Wait until there is an empty slot


WaitForSingleObject(emptySemaphore, INFINITE);

// Lock the buffer


WaitForSingleObject(mutex, INFINITE);

buffer[in] = item;
printf("Producer produced: %d (at index %d)\n", item, in);
in = (in + 1) % BUFFER_SIZE;

// Unlock the buffer


ReleaseMutex(mutex);

// Signal that a new item is available


ReleaseSemaphore(fullSemaphore, 1, NULL);

Sleep(1000); // Simulate production time


}
return 0;
}
// Consumer function
DWORD WINAPI Consumer(LPVOID lpParam) {
int item;
for (int i = 1; i <= 10; i++) {
// Wait until there is a filled slot
WaitForSingleObject(fullSemaphore, INFINITE);

// Lock the buffer


WaitForSingleObject(mutex, INFINITE);

item = buffer[out];
printf("Consumer consumed: %d (from index %d)\n", item, out);
out = (out + 1) % BUFFER_SIZE;

// Unlock the buffer


ReleaseMutex(mutex);

// Signal that a slot is free


ReleaseSemaphore(emptySemaphore, 1, NULL);

Sleep(2000); // Simulate consumption time


}
return 0;
}

int main() {
HANDLE hProducer, hConsumer;

// Create synchronization objects


mutex = CreateMutex(NULL, FALSE, NULL);
emptySemaphore = CreateSemaphore(NULL, BUFFER_SIZE, BUFFER_SIZE, NULL); //
Initially buffer is empty
fullSemaphore = CreateSemaphore(NULL, 0, BUFFER_SIZE, NULL); // Initially
buffer is empty

// Create producer and consumer threads


hProducer = CreateThread(NULL, 0, Producer, NULL, 0, NULL);
hConsumer = CreateThread(NULL, 0, Consumer, NULL, 0, NULL);

// Wait for both threads to finish


WaitForSingleObject(hProducer, INFINITE);
WaitForSingleObject(hConsumer, INFINITE);
// Cleanup
CloseHandle(hProducer);
CloseHandle(hConsumer);
CloseHandle(mutex);
CloseHandle(emptySemaphore);
CloseHandle(fullSemaphore);

printf("\n? Producer-Consumer simulation completed.\n");

return 0;
}
Assignment No 4
Part B

#include <stdio.h>
#include <windows.h>

int readCount = 0; // Number of active readers


HANDLE mutex; // Protects readCount
HANDLE rw_mutex; // Ensures mutual exclusion for writers

// ---------------- Reader Thread ----------------


DWORD WINAPI Reader(LPVOID lpParam) {
int id = (int)(size_t)lpParam; // Reader ID

// Entry section
WaitForSingleObject(mutex, INFINITE); // Lock readCount
readCount++;
if (readCount == 1) {
// First reader locks the resource
WaitForSingleObject(rw_mutex, INFINITE);
}
ReleaseMutex(mutex); // Unlock readCount

// Critical section (Reading)


printf("Reader %d is reading. Active readers = %d\n", id, readCount);
Sleep(1000); // Simulate reading

// Exit section
WaitForSingleObject(mutex, INFINITE);
readCount--;
if (readCount == 0) {
// Last reader unlocks the resource
ReleaseMutex(rw_mutex);
}
ReleaseMutex(mutex);

return 0;
}

// ---------------- Writer Thread ----------------


DWORD WINAPI Writer(LPVOID lpParam) {
int id = (int)(size_t)lpParam; // Writer ID
// Entry section
WaitForSingleObject(rw_mutex, INFINITE); // Lock the resource

// Critical section (Writing)


printf("Writer %d is writing...\n", id);
Sleep(2000); // Simulate writing

// Exit section
ReleaseMutex(rw_mutex);

return 0;
}

int main() {
HANDLE readers[5], writers[2];

// Create synchronization objects


mutex = CreateMutex(NULL, FALSE, NULL);
rw_mutex = CreateMutex(NULL, FALSE, NULL);

// Create 5 reader threads


for (int i = 0; i < 5; i++) {
readers[i] = CreateThread(NULL, 0, Reader, (LPVOID)(size_t)(i+1), 0, NULL);
}

// Create 2 writer threads


for (int i = 0; i < 2; i++) {
writers[i] = CreateThread(NULL, 0, Writer, (LPVOID)(size_t)(i+1), 0, NULL);
}

// Wait for all reader threads


WaitForMultipleObjects(5, readers, TRUE, INFINITE);
// Wait for all writer threads
WaitForMultipleObjects(2, writers, TRUE, INFINITE);

// Cleanup
for (int i = 0; i < 5; i++) CloseHandle(readers[i]);
for (int i = 0; i < 2; i++) CloseHandle(writers[i]);
CloseHandle(mutex);
CloseHandle(rw_mutex);
printf("\n? Reader-Writer simulation completed.\n");
return 0;
}
Assignment No 5

#include <stdio.h>

int n, m; // n = number of processes, m = number of resources

void display(int mat[5][3]) {


for (int i = 0; i < n; i++) {
printf("\n");
for (int j = 0; j < m; j++) {
printf("%d ", mat[i][j]);
}
}
}

int main() {
printf("\n\n Enter number of processes: ");
scanf("%d", &n);
printf("\n\n Enter number of resources: ");
scanf("%d", &m);

int alloc[5][3], need[5][3], max[5][3];


int available[3];

printf("\n\n Enter Allocation Matrix:\n");


for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%d", &alloc[i][j]);
}
}

printf("\n\n Enter Max Matrix:\n");


for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%d", &max[i][j]);
}
}

printf("\n\n Enter Available Array:\n");


for (int i = 0; i < m; i++) {
scanf("%d", &available[i]);
}
// Displaying matrices and available array
printf("\n\n Displaying Allocation Matrix:");
display(alloc);

printf("\n\n Displaying Max Matrix:");


display(max);

printf("\n\n Displaying Available Array:\n");


for (int i = 0; i < m; i++) {
printf("%d ", available[i]);
}

// Step 1: Creating Need matrix


for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
need[i][j] = max[i][j] - alloc[i][j];
}
}

printf("\n\n Displaying Need Matrix:");


display(need);

// Step 2: Initializing flag array to keep track of process completion


int flag[5] = {0}; // 0 means not finished, 1 means finished
int safe_seq[5]; // Array to store the safe sequence
int ct = 0; // Counter for the safe sequence

// Step 3: Find a safe sequence


for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
if (flag[i] == 0) { // If the process hasn't finished yet
int can_allocate = 1;

// Check if the process can be allocated resources


for (int j = 0; j < m; j++) {
if (need[i][j] > available[j]) {
can_allocate = 0;
break;
}
}

// If the process can be allocated


if (can_allocate) {
// Mark the process as finished
flag[i] = 1;

// Add process to the safe sequence


safe_seq[ct++] = i;

// Update the available resources


for (int j = 0; j < m; j++) {
available[j] += alloc[i][j];
}

break; // Start over to find the next process


}
}
}
}

// Step 4: Checking if Safe Sequence is present or not


int found_safe_sequence = 1;
for (int i = 0; i < n; i++) {
if (flag[i] == 0) { // If any process is not completed
found_safe_sequence = 0;
break;
}
}

// Printing Safe Sequence


if (found_safe_sequence) {
printf("\n\n Safe Sequence: ");
for (int i = 0; i < ct; i++) {
printf("P%d", safe_seq[i] + 1); // Display process numbers starting from P1
if (i < ct - 1) {
printf(", ");
}
}
} else {
printf("\n\n Safe Sequence Not Present!");
}

return 0;
}
Assignmeny No 6

#include <stdio.h>

#define MAX_FRAMES 10
#define MAX_PAGES 30

// Function prototypes
void fcfs(int pages[], int n, int frames);
void lru(int pages[], int n, int frames);
void optimal(int pages[], int n, int frames);

int main() {
int pages[MAX_PAGES], n, frames, i, choice;

printf("Enter number of pages: ");


scanf("%d", &n);

printf("Enter the reference string: ");


for (i = 0; i < n; i++) {
scanf("%d", &pages[i]);
}

printf("Enter number of frames (>=3): ");


scanf("%d", &frames);

if (frames < 3) {
printf("Minimum frame size should be 3!\n");
return 0;
}

while (1) {
printf("\nPage Replacement Algorithms Menu:\n");
printf("1. FCFS\n");
printf("2. LRU\n");
printf("3. Optimal\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
fcfs(pages, n, frames);
break;
case 2:
lru(pages, n, frames);
break;
case 3:
optimal(pages, n, frames);
break;
case 4:
return 0;
default:
printf("Invalid choice!\n");
}
}
return 0;
}

// ---------- FCFS ----------


void fcfs(int pages[], int n, int frames) {
int frame[MAX_FRAMES], front = 0, count = 0, faults = 0;
for (int i = 0; i < frames; i++)
frame[i] = -1;

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


int flag = 0;
for (int j = 0; j < count; j++) {
if (frame[j] == pages[i]) {
flag = 1;
break;
}
}
if (!flag) {
frame[front] = pages[i];
front = (front + 1) % frames;
if (count < frames) count++;
faults++;
}
printf("Page %d -> ", pages[i]);
for (int k = 0; k < frames; k++) {
if (frame[k] != -1) printf("%d ", frame[k]);
else printf("- ");
}
printf("\n");
}
printf("Total Page Faults (FCFS) = %d\n", faults);
}

// ---------- LRU ----------


void lru(int pages[], int n, int frames) {
int frame[MAX_FRAMES], used[MAX_FRAMES], count = 0, faults = 0;
for (int i = 0; i < frames; i++)
frame[i] = -1;

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


int flag = 0, j;
for (j = 0; j < count; j++) {
if (frame[j] == pages[i]) {
flag = 1;
used[j] = i; // update last used
break;
}
}
if (!flag) {
if (count < frames) {
frame[count] = pages[i];
used[count] = i;
count++;
} else {
int lru_index = 0;
for (j = 1; j < frames; j++) {
if (used[j] < used[lru_index]) lru_index = j;
}
frame[lru_index] = pages[i];
used[lru_index] = i;
}
faults++;
}
printf("Page %d -> ", pages[i]);
for (int k = 0; k < frames; k++) {
if (frame[k] != -1) printf("%d ", frame[k]);
else printf("- ");
}
printf("\n");
}
printf("Total Page Faults (LRU) = %d\n", faults);
}
// ---------- Optimal ----------
void optimal(int pages[], int n, int frames) {
int frame[MAX_FRAMES], count = 0, faults = 0;
for (int i = 0; i < frames; i++)
frame[i] = -1;

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


int flag = 0, j;
for (j = 0; j < count; j++) {
if (frame[j] == pages[i]) {
flag = 1;
break;
}
}
if (!flag) {
if (count < frames) {
frame[count] = pages[i];
count++;
} else {
int index = -1, farthest = i + 1;
for (j = 0; j < frames; j++) {
int k;
for (k = i + 1; k < n; k++) {
if (frame[j] == pages[k]) {
if (k > farthest) {
farthest = k;
index = j;
}
break;
}
}
if (k == n) { // not found in future
index = j;
break;
}
}
if (index == -1) index = 0;
frame[index] = pages[i];
}
faults++;
}
printf("Page %d -> ", pages[i]);
for (int k = 0; k < frames; k++) {
if (frame[k] != -1) printf("%d ", frame[k]);
else printf("- ");
}
printf("\n");
}
printf("Total Page Faults (Optimal) = %d\n", faults);
}
Assignment No 7
Part A

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main() {
int pipe1[2], pipe2[2]; // Two arrays for two pipes
pid_t pid;
char parent_msg[] = "Message from Parent to Child";
char child_msg[] = "Message from Child to Parent";
char buffer[100];

// Creating first pipe (for Parent to Child communication)


if (pipe(pipe1) == -1) {
perror("Pipe1 creation failed");
exit(1);
}

// Creating second pipe (for Child to Parent communication)


if (pipe(pipe2) == -1) {
perror("Pipe2 creation failed");
exit(1);
}

// Fork to create child process


pid = fork();

if (pid < 0) {
perror("Fork failed");
exit(1);
}

if (pid > 0) { // Parent Process


// Close unnecessary pipe ends
close(pipe1[0]); // Close read end of pipe1 (parent to child)
close(pipe2[1]); // Close write end of pipe2 (child to parent)

// Send a message to the child via pipe1


write(pipe1[1], parent_msg, strlen(parent_msg) + 1);
close(pipe1[1]); // Close write end after writing
// Read the message from the child via pipe2
read(pipe2[0], buffer, sizeof(buffer));
printf("Parent received: %s\n", buffer);
close(pipe2[0]); // Close read end after reading

} else { // Child Process


// Close unnecessary pipe ends
close(pipe1[1]); // Close write end of pipe1 (parent to child)
close(pipe2[0]); // Close read end of pipe2 (child to parent)

// Read the message from the parent via pipe1


read(pipe1[0], buffer, sizeof(buffer));
printf("Child received: %s\n", buffer);
close(pipe1[0]); // Close read end after reading

// Send a message to the parent via pipe2


write(pipe2[1], child_msg, strlen(child_msg) + 1);
close(pipe2[1]); // Close write end after writing
}

return 0;
}
Output :
Assignment No 7
Part B

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

#define SHM_NAME "/MySharedMemory"


#define SHM_SIZE 4 * sizeof(int)

void do_client(int *shm_ptr);

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


int shm_fd;
int *shm_ptr;
pid_t pid;

if (argc == 5) {
// Server (parent) process
shm_fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, 0666);
if (shm_fd == -1) {
perror("shm_open");
exit(1);
}

if (ftruncate(shm_fd, SHM_SIZE) == -1) {


perror("ftruncate");
exit(1);
}

shm_ptr = mmap(0, SHM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED,


shm_fd, 0);
if (shm_ptr == MAP_FAILED) {
perror("mmap");
exit(1);
}

printf("Parent Process (Server) PID=%d\n", getpid());


// Write data to shared memory
shm_ptr[0] = atoi(argv[1]);
shm_ptr[1] = atoi(argv[2]);
shm_ptr[2] = atoi(argv[3]);
shm_ptr[3] = atoi(argv[4]);

printf("Server has produced %d %d %d %d items in shared memory.\n",


shm_ptr[0], shm_ptr[1], shm_ptr[2], shm_ptr[3]);

// Fork a child process


pid = fork();

if (pid < 0) {
perror("fork");
exit(1);
}

if (pid == 0) {
// Child process
execl(argv[0], argv[0], "child", NULL);
perror("execl");
exit(1);
} else {
// Parent waits
waitpid(pid, NULL, 0);
printf("Child Process has finished.\n");

// Cleanup
munmap(shm_ptr, SHM_SIZE);
shm_unlink(SHM_NAME);

printf("Server exits.\n");
}
} else if (argc == 2 && strcmp(argv[1], "child") == 0) {
// Child process (client)
shm_fd = shm_open(SHM_NAME, O_RDWR, 0666);
if (shm_fd == -1) {
perror("shm_open");
exit(1);
}
shm_ptr = mmap(0, SHM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED,
shm_fd, 0);
if (shm_ptr == MAP_FAILED) {
perror("mmap");
exit(1);
}

do_client(shm_ptr);

munmap(shm_ptr, SHM_SIZE);
close(shm_fd);
} else {
printf("Usage: %s #1 #2 #3 #4\n", argv[0]);
exit(1);
}

return 0;
}

void do_client(int *shm_ptr) {


printf("Child started as Client PID=%d\n", getpid());
printf("Client consumed %d %d %d %d from shared memory\n",
shm_ptr[0], shm_ptr[1], shm_ptr[2], shm_ptr[3]);
printf("Client terminated.\n");
}

Output :
Assignment No 8

#include <stdio.h>
#include <stdlib.h>
#define MAX 100
// Function to calculate absolute value
int absolute(int x) {
return (x < 0) ? -x : x;
}
// SSTF Disk Scheduling Algorithm
void sstf(int requests[], int n, int head) {
int i, j, seek = 0, min, pos, diff;
int completed[MAX] = {0}; // To keep track of processed requests
printf("\nSSTF Disk Scheduling:\n");
for (i = 0; i < n; i++) {
min = 10000;
for (j = 0; j < n; j++) {
if (!completed[j]) {
diff = absolute(requests[j] - head);
if (diff < min) {
min = diff;
pos = j;
}
}
}
completed[pos] = 1; // Mark request as processed
seek += min;
printf("Move from %d to %d with seek %d\n", head, requests[pos], min);
head = requests[pos];
}
printf("Total Seek Time: %d\n", seek);
}

// SCAN Disk Scheduling Algorithm (Elevator Algorithm)


void scan(int requests[], int n, int head, int disk_size) {
int i, j, seek = 0;
int direction = 1; // Moving towards the end of the disk
printf("\nSCAN Disk Scheduling:\n");

// Sort the requests array


for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (requests[i] > requests[j]) {
int temp = requests[i];
requests[i] = requests[j];
requests[j] = temp;
}
}
}

// Scan towards the right (end of the disk)


for (i = 0; i < n; i++) {
if (requests[i] >= head) {
break;
}
}

// Moving to the right


for (j = i; j < n; j++) {
printf("Move from %d to %d with seek %d\n", head, requests[j],
absolute(requests[j] - head));
seek += absolute(requests[j] - head);
head = requests[j];
}

// Move to the end of the disk


if (direction) {
printf("Move from %d to %d with seek %d\n", head, disk_size - 1,
absolute(disk_size - 1 - head));
seek += absolute(disk_size - 1 - head);
head = disk_size - 1;
}

// Moving back to the left


for (j = i - 1; j >= 0; j--) {
printf("Move from %d to %d with seek %d\n", head, requests[j],
absolute(requests[j] - head));
seek += absolute(requests[j] - head);
head = requests[j];
}
printf("Total Seek Time: %d\n", seek);
}

// C-LOOK Disk Scheduling Algorithm


void c_look(int requests[], int n, int head) {
int i, j, seek = 0;
printf("\nC-LOOK Disk Scheduling:\n");

// Sort the requests array


for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (requests[i] > requests[j]) {
int temp = requests[i];
requests[i] = requests[j];
requests[j] = temp;
}
}
}

// Find the starting point for scanning to the right


for (i = 0; i < n; i++) {
if (requests[i] >= head) {
break;
}
}

// Move to the right


for (j = i; j < n; j++) {
printf("Move from %d to %d with seek %d\n", head, requests[j],
absolute(requests[j] - head));
seek += absolute(requests[j] - head);
head = requests[j];
}

// Jump to the first request


if (i != 0) {
printf("Jump from %d to %d\n", head, requests[0]);
head = requests[0];
}

// Move to the right from the beginning


for (j = 0; j < i; j++) {
printf("Move from %d to %d with seek %d\n", head, requests[j],
absolute(requests[j] - head));
seek += absolute(requests[j] - head);
head = requests[j];
}
printf("Total Seek Time: %d\n", seek);
}

int main() {
int n, head, disk_size;

printf("Enter the number of disk requests: ");


scanf("%d", &n);

int requests[MAX];
printf("Enter the disk requests: ");
for (int i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}

printf("Enter the initial head position: ");


scanf("%d", &head);

printf("Enter the disk size: ");


scanf("%d", &disk_size);
sstf(requests, n, head);
scan(requests, n, head, disk_size);
c_look(requests, n, head);
return 0;
}

You might also like