Aos
Program 1: (system call unix os)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
int main() {
// Print the current process ID
printf("Current process PID: %d\n", getpid());
// Perform directory operations
DIR *dir;
struct dirent *entry;
struct stat file_stat;
dir = opendir(".");
if (dir == NULL) {
perror("opendir failed");
exit(EXIT_FAILURE);
}
// Read directory entries
while ((entry = readdir(dir)) != NULL) {
// Print the name of the file
printf("File: %s\n", entry->d_name);
// Get file status
if (stat(entry->d_name, &file_stat) == 0) {
printf("File size: %ld bytes\n", (long)file_stat.st_size);
printf("File mode: %o\n", file_stat.st_mode & 0777);
} else {
perror("stat failed");
}
}
// Close the directory
closedir(dir);
// Replace the current process image with `ls` command
execlp("ls", "ls", "-l", (char *)NULL);
// If execlp fails
perror("execlp failed");
exit(EXIT_FAILURE);
}
Program 2: (I/O system calls)
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
int main()
{
int fd, sz;
char buffer[100]; // Buffer to read the file content
char *new_content = "Additional message: Enjoy your learning!\n";
// Open the file for reading and writing
fd = open("foo.txt", O_RDWR);
if (fd < 0)
{
perror("r1");
exit(1);
}
// Read the existing content of the file
sz = read(fd, buffer, sizeof(buffer) - 1);
if (sz < 0)
{
perror("read");
close(fd);
exit(1);
}
buffer[sz] = '\0'; // Null-terminate the buffer
// Print the existing content
printf("Existing content of foo.txt:\n%s\n", buffer);
// Move the file offset to the end of the file
if (lseek(fd, 0, SEEK_END) < 0)
{
perror("lseek");
close(fd);
exit(1);
}
// Write new content to the file
sz = write(fd, new_content, strlen(new_content));
if (sz < 0)
{
perror("write");
close(fd);
exit(1);
}
printf("Called write(%d, \"%s\", %lu). It returned %d\n", fd, new_content, strlen(new_content), sz);
close(fd);
return 0;
}
Output:
Program3 : (unix commands)
lS
#include <stdio.h>
#include <dirent.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
// Open current directory if no directory path is provided
if (argc < 2) {
dir = opendir("Y://");
} else {
// Open the specified directory
dir = opendir(argv[1]);
}
if (dir == NULL) {
perror("opendir");
return 1;
}
// Read directory entries and print them
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
Grap.c
#include<stdio.h>
#include<string.h>
void main()
{
char fn[10],pat[10],temp[200];
FILE *fp;
printf("Enter file name\n");
scanf("%s",fn);
printf("Enter pattern to be searched\n");
scanf("%s",pat);
fp=fopen(fn,"r");
while(!feof(fp))
{
fgets(temp,1000,fp);
if(strstr(temp,pat))
printf("%s",temp);
}
fclose(fp);
}
Program 4: (agntt chart or fcfs an sjf)
#include <stdio.h>
typedef struct {
int id, burst, arrival, wait, turnaround;
} Process;
void fcfs(Process procs[], int n) {
int time = 0,i;
for (i = 0; i < n; i++) {
if (time < procs[i].arrival) time = procs[i].arrival;
procs[i].wait = time - procs[i].arrival;
procs[i].turnaround = procs[i].wait + procs[i].burst;
time += procs[i].burst;
}
}
void sjf(Process procs[], int n) {
int time = 0,i,j;
for ( i = 0; i < n; i++) {
int min_burst_idx = i;
for ( j = i + 1; j < n; j++) {
if (procs[j].arrival <= time && procs[j].burst < procs[min_burst_idx].burst) {
min_burst_idx = j;
}
}
Process temp = procs[i];
procs[i] = procs[min_burst_idx];
procs[min_burst_idx] = temp;
if (time < procs[i].arrival) time = procs[i].arrival;
procs[i].wait = time - procs[i].arrival;
procs[i].turnaround = procs[i].wait + procs[i].burst;
time += procs[i].burst;
}
}
void print_stats(Process procs[], int n) {
double total_wait = 0, total_turnaround = 0;
int i;
for ( i = 0; i < n; i++) {
printf("P%d ", procs[i].id);
total_wait += procs[i].wait;
total_turnaround += procs[i].turnaround;
}
printf("\nAverage waiting time: %.2f\n", total_wait / n);
printf("Average turnaround time: %.2f\n", total_turnaround / n);
}
int main() {
Process procs[] = {{1, 6, 0, 0, 0}, {2, 8, 1, 0, 0}, {3, 7, 2, 0, 0}, {4, 3, 3, 0, 0}};
int n = sizeof(procs) / sizeof(procs[0]);
printf("FCFS Scheduling\n");
fcfs(procs, n);
print_stats(procs, n);
int i;
// Reset for SJF
for ( i = 0; i < n; i++) procs[i].wait = procs[i].turnaround = 0;
printf("\nSJF Scheduling\n");
sjf(procs, n);
print_stats(procs, n);
return 0;}
Program 5: (gantt chart for priority and round robin )
#include <stdio.h>
struct Process {
int id, at, bt, prio, rt, wt, tat, ct;
};
void calcTimes(int n, struct Process p[]) {
int i;
for ( i = 0; i < n; i++) {
p[i].tat = p[i].ct - p[i].at;
p[i].wt = p[i].tat - p[i].bt;
}
}
void priorityScheduling(int n, struct Process p[]) {
int time = 0, completed = 0;
while (completed < n) {
int idx = -1, highPrio = 1e9,i;
for ( i = 0; i < n; i++) {
if (p[i].at <= time && p[i].prio < highPrio && p[i].ct == 0) {
highPrio = p[i].prio;
idx = i;
}
}
if (idx != -1) {
time += p[idx].bt;
p[idx].ct = time;
completed++;
} else {
time++;
}
}
}
void roundRobin(int n, struct Process p[], int q) {
int time = 0, completed = 0,i;
while (completed < n) {
for ( i = 0; i < n; i++) {
if (p[i].rt > 0) {
int burst = p[i].rt > q ? q : p[i].rt;
time += burst;
p[i].rt -= burst;
if (p[i].rt == 0) {
p[i].ct = time;
completed++;
}
}
}
}
}
void printResults(int n, struct Process p[], const char* policy) {
double totalWT = 0, totalTAT = 0;
printf("%s Gantt Chart: ", policy);
int i;
for (i = 0; i < n; i++) {
printf("| P%d ", p[i].id);
totalWT += p[i].wt;
totalTAT += p[i].tat;
}
printf("|\n%s - Avg WT: %.2f\n%s - Avg TAT: %.2f\n", policy, totalWT / n, policy, totalTAT / n);
}
int main() {
int n = 4, q = 2;
struct Process p1[] = {{1, 0, 8, 3, 8}, {2, 1, 4, 1, 4}, {3, 2, 9, 2, 9}, {4, 3, 5, 4, 5}};
struct Process p2[] = {{1, 0, 8, 0, 8}, {2, 1, 4, 0, 4}, {3, 2, 9, 0, 9}, {4, 3, 5, 0, 5}};
priorityScheduling(n, p1);
calcTimes(n, p1);
printResults(n, p1, "Priority");
roundRobin(n, p2, q);
calcTimes(n, p2);
printResults(n, p2, "Round Robin");
return 0;
}
Program 6: (file management )
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_FILENAME_LENGTH 100
#define MAX_CONTENT_LENGTH 1000
// Structure to represent a file
typedef struct {
char filename[MAX_FILENAME_LENGTH];
FILE* file;
} File;
// Function to open a file
void open_file(File* file) {
printf("Enter filename: ");
fgets(file->filename, MAX_FILENAME_LENGTH, stdin);
file->filename[strcspn(file->filename, "\n")] = 0; // Remove newline character
file->file = fopen(file->filename, "w+");
if (file->file == NULL) {
printf("Error opening file\n");
exit(1);
}
printf("File opened successfully\n");
}
// Function to write to a file
void write_to_file(File* file) {
if (file->file == NULL) {
printf("Please open a file first\n");
return;
}
char content[MAX_CONTENT_LENGTH];
printf("Enter content to write: ");
fgets(content, MAX_CONTENT_LENGTH, stdin);
content[strcspn(content, "\n")] = 0; // Remove newline character
fprintf(file->file, "%s", content);
fflush(file->file);
printf("Content written to file\n");
printf("Write command executed\n");
}
// Function to read from a file
void read_from_file(File* file) {
if (file->file == NULL) {
printf("Please open a file first\n");
return;
}
rewind(file->file);
char content[MAX_CONTENT_LENGTH];
fread(content, 1, MAX_CONTENT_LENGTH, file->file);
content[MAX_CONTENT_LENGTH - 1] = '\0'; // Ensure null-termination
printf("%s\n", content);
}
// Function to close a file
void delete_file(File* file) {
if (file->file == NULL) {
printf("No file is open\n");
return;
}
fclose(file->file);
file->file = NULL;
printf("File Deleted\n");
}
// Function to exit the program
void exit_program(File* file) {
if (file->file != NULL) {
delete_file(file);
}
printf("Exiting program\n");
}
int main() {
File file;
file.file = NULL;
while (1) {
printf("\nEnter command (open, read, write, delete, exit): ");
char command[10];
fgets(command, 10, stdin);
command[strcspn(command, "\n")] = 0; // Remove newline character
if (strcmp(command, "open") == 0) {
open_file(&file);
} else if (strcmp(command, "write") == 0) {
write_to_file(&file);
} else if (strcmp(command, "read") == 0) {
read_from_file(&file);
} else if (strcmp(command, "delete") == 0) {
delete_file(&file);
} else if (strcmp(command, "exit") == 0) {
exit_program(&file);
break;
} else {
printf("Invalid command. Please try again.\n");
}
}
return 0;
}
Program 7: (semaphore)
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 5
int buffer[BUFFER_SIZE];
int in = 0, out = 0;
int items_to_produce, items_to_consume;
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 critical section
void *producer(void *arg) {
int i,item;
for ( i = 0; i < items_to_produce; i++) {
item = rand() % 100; // Produce a random item
sem_wait(&empty); // Wait for an empty slot
pthread_mutex_lock(&mutex); // Lock the critical section
buffer[in] = item;
printf("Produced: %d\n", item);
in = (in + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex); // Unlock the critical section
sem_post(&full); // Signal that a slot is full
}
pthread_exit(NULL);
}
void *consumer(void *arg) {
int i,item;
for (i = 0; i < items_to_consume; i++) {
sem_wait(&full); // Wait for a full slot
pthread_mutex_lock(&mutex); // Lock the critical section
item = buffer[out];
printf("Consumed: %d\n", item);
out = (out + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex); // Unlock the critical section
sem_post(&empty); // Signal that a slot is empty
}
pthread_exit(NULL);
}
int main() {
pthread_t prod, cons;
printf("Enter the number of items to produce: ");
scanf("%d", &items_to_produce);
printf("Enter the number of items to consume: ");
scanf("%d", &items_to_consume);
if (items_to_consume > items_to_produce) {
printf("Error: Cannot consume more items than produced!\n");
return -1;
}
sem_init(&empty, 0, BUFFER_SIZE); // Initialize semaphore for empty slots
sem_init(&full, 0, 0); // Initialize semaphore for full slots
pthread_mutex_init(&mutex, NULL); // Initialize the mutex
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;
}
Program 8: (demand paging)
#include <stdio.h>
int main() {
int PAGES, FRAMES;
printf("Enter the number of pages: ");
scanf("%d", &PAGES);
printf("Enter the number of frames: ");
scanf("%d", &FRAMES);
int referenceString[PAGES];
int frames[FRAMES];
int pageFaults = 0;
int i, j;
int lruIndex = 0; // Index of the least recently used frame
int time[FRAMES]; // Array to store the time of use for each frame
// Initialize the frames and time arrays
for (i = 0; i < FRAMES; i++) {
frames[i] = -1;
time[i] = 0;
}
printf("Enter the reference string (space-separated): ");
for (i = 0; i < PAGES; i++) {
scanf("%d", &referenceString[i]);
}
for (i = 0; i < PAGES; i++) {
int page = referenceString[i];
int found = 0;
// Check if the page is already in the frames
for (j = 0; j < FRAMES; j++) {
if (frames[j] == page) {
found = 1;
// Update the time of use for the page
time[j] = i;
break;
}
}
if (!found) {
// Find the least recently used frame
int minTime = time[0];
lruIndex = 0;
for (j = 1; j < FRAMES; j++) {
if (time[j] < minTime) {
minTime = time[j];
lruIndex = j;
}
}
// Replace the least recently used frame with the new page
frames[lruIndex] = page;
time[lruIndex] = i;
pageFaults++;
}
printf("Page %d: ", page);
for (j = 0; j < FRAMES; j++) {
printf("%d ", frames[j]);
}
printf("\n");
}
printf("Total page faults: %d\n", pageFaults);
// Find the least recently used page
int minTime = time[0];
lruIndex = 0;
for (i = 1; i < FRAMES; i++) {
if (time[i] < minTime) {
minTime = time[i];
lruIndex = i;
}
}
printf("Least recently used page: %d\n", frames[lruIndex]);
return 0;
}
Program 09: (File allocation)
#include <stdio.h>
#include <stdlib.h>
#define DISK_SIZE 100
int main() {
int disk[DISK_SIZE] = {0}; // Initialize disk blocks as free (0)
int fileSizes[] = {15, 10, 8, 12};
int fileCount = sizeof(fileSizes) / sizeof(fileSizes[0]);
int i,j,k, startBlock = 0;
for (i = 0; i <fileCount; i++) {
int fileSize = fileSizes[i];
int allocated = 0;
for (j = startBlock; j<DISK_SIZE - fileSize; j++) {
int freeSpace = 0;
for ( k = 0; k<fileSize; k++) {
if (disk[j + k] == 0) {
freeSpace++;
} else {
break;
}
}
if (freeSpace == fileSize) {
startBlock = j + fileSize;
for (k = 0; k < fileSize; k++) {
disk[j + k] = 1; // Allocate blocks
}
printf("File %d allocated from block %d to %d\n", i + 1, j, j + fileSize - 1);
allocated = 1;
break;
}
}
if (!allocated) {
printf("File %d allocation failed\n", i + 1);
}
}
return 0;
}
Program10: (deadlock avoidance)
#include <stdio.h>
#define MAX_PROCESS 10
#define MAX_RESOURCE 10
int main() {
int n, m, i, j, k;
int allocation[MAX_PROCESS][MAX_RESOURCE],
max[MAX_PROCESS][MAX_RESOURCE], available[MAX_RESOURCE];
int need[MAX_PROCESS][MAX_RESOURCE], finish[MAX_PROCESS],
safeSeq[MAX_PROCESS], work[MAX_RESOURCE];
printf("Enter the number of processes: ");
scanf("%d", &n);
printf("Enter the number of resources: ");
scanf("%d", &m);
printf("Enter the allocation matrix:\n");
for (i = 0; i < n; ++i) {
for (j = 0; j < m; ++j) {
scanf("%d", &allocation[i][j]);
}
}
printf("Enter the maximum matrix:\n");
for (i = 0; i < n; ++i) {
for (j = 0; j < m; ++j) {
scanf("%d", &max[i][j]);
}
}
printf("Enter the available resources:\n");
for (i = 0; i < m; ++i) {
scanf("%d", &available[i]);
}
// Initialize finish array
for (i = 0; i < n; ++i) {
finish[i] = 0;
}
// Calculate need matrix
for (i = 0; i < n; ++i) {
for (j = 0; j < m; ++j) {
need[i][j] = max[i][j] - allocation[i][j];
}
}
// Initialize work array with available resources
for (i = 0; i < m; ++i) {
work[i] = available[i];
}
int count = 0;
while (count < n) {
int found = 0;
for (i = 0; i < n; ++i) {
if (finish[i] == 0) {
int flag = 1;
for (j = 0; j < m; ++j) {
if (need[i][j] > work[j]) {
flag = 0;
break;
}
}
if (flag) {
for (k = 0; k < m; ++k) {
work[k] += allocation[i][k];
}
safeSeq[count++] = i;
finish[i] = 1;
found = 1;
}
}
}
if (!found) {
printf("System is not in a safe state!\n");
return 0;
}
}
printf("System is in a safe state.\n ");
return 0;
}
Comments
Post a Comment