WEEK-4
Write a C program to implement the Producer-Consumer problem using semaphores using
UNIX/LINUX system calls.
Aim:
Write a C program to implement the Producer-Consumer problem using semaphores using
UNIX/LINUX system calls.
Algorithm:
1. The Semaphore mutex, full & empty is initialized.
2. In the case of producer process
3. Produce an item in a temporary variable.
If there is empty space in the buffer check the mutex value to enter into the critical section.
If the mutex value is 0, allow the producer to add value in the temporary variable to the
buffer.
4. In the case of consumer process
i) It should wait if the buffer is empty
ii) If there is any item in the buffer check for mutex value, if the mutex==0, remove
item from buffer
iii) Signal the mutex value and reduce the empty value by 1.
iv) Consume the item.
5. Print the result
Program:
#include<stdio.h>
#include<stdlib.h>
int mutex = 1, full = 0, empty = 3, x = 0;
int main ()
{
int n;
void producer ();
void consumer ();
int wait (int);
int signal (int);
printf ("\n1.Producer\n2.Consumer\n3.Exit");
while (1)
{
printf ("\nEnter your choice:");
scanf ("%d", &n);
switch (n)
{
case 1:
if ((mutex == 1) && (empty != 0))
producer ();
else
printf ("Buffer is full!!");
break;
case 2:
if ((mutex == 1) && (full != 0))
consumer ();
else
printf ("Buffer is empty!!");
break;
case 3:
exit (0);
break;
}
}
return 0;
}
int wait (int s)
{
return (--s);
}
int signal (int s)
{
return (++s);
}
void producer ()
{
mutex = wait (mutex);
full = signal (full);
empty = wait (empty);
x++;
printf ("\nProducer produces the item %d", x);
mutex = signal (mutex);
}
void consumer ()
{
mutex = wait (mutex);
full = wait (full);
empty = signal (empty);
printf ("\nConsumer consumes item %d", x);
x--;
mutex = signal (mutex);
}
Output:
Week: 5
Write C programs to illustrate the following IPC mechanisms
Aim: Write C programs to illustrate the following IPC mechanisms
ALGORITHM:
1. Start the program.
2. Declare the variables.
3. Read the choice.
4. Create a piping processing using IPC.
5. Assign the variable lengths
6. “strcpy” the message lengths.
7. To join the operation using IPC .
8. Stop the program
Program :
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MSG_LEN 64
int main() {
int result;
int fd[2];
char message[MSG_LEN];
char recvd_msg[MSG_LEN];
// Creating the pipe
result = pipe(fd);
if (result < 0) {
perror("pipe");
exit(1);
}
// Write first message to the pipe
strncpy(message, "Kumar Chinthala,", MSG_LEN - 1);
message[MSG_LEN - 1] = '\0'; // Ensure null termination
result = write(fd[1], message, strlen(message));
if (result < 0) {
perror("write");
exit(2);
}
// Write second message to the pipe
strncpy(message, "CSE-DS,", MSG_LEN - 1);
message[MSG_LEN - 1] = '\0'; // Ensure null termination
result = write(fd[1], message, strlen(message));
if (result < 0) {
perror("write");
exit(2);
}
// Write third message to the pipe
strncpy(message, "MRCE,", MSG_LEN - 1);
message[MSG_LEN - 1] = '\0'; // Ensure null termination
result = write(fd[1], message, strlen(message));
if (result < 0) {
perror("write");
exit(2);
}
// Write fourth message to the pipe
strncpy(message, "Hyderabad", MSG_LEN - 1);
message[MSG_LEN - 1] = '\0'; // Ensure null termination
result = write(fd[1], message, strlen(message));
if (result < 0) {
perror("write");
exit(2);
}
// Close the write end of the pipe after writing all messages
close(fd[1]);
// Read from the pipe
result = read(fd[0], recvd_msg, MSG_LEN - 1);
if (result < 0) {
perror("read");
exit(3);
}
recvd_msg[result] = '\0'; // Null terminate the received message
// Print the received message
printf("Received message: %s\n", recvd_msg);
return 0;
}
Output:
a) FIFO
Program:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <linux/stat.h>
#define FIFO_FILE "fifo.txt"
int main(void)
{
FILE *fp;
char readbuf[80];
/* Create the FIFO if it does not exist */
umask(0);
mknod(FIFO_FILE, S_IFIFO|0666, 0);
while(1)
{
fp = fopen(FIFO_FILE, "r");
fgets(readbuf, 80, fp);
printf("Received string: %s \n", readbuf);
fclose(fp);
}
return(0);
}
OUTPUT:
C) Message Queue (Writer Process)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
// structure for message queue
struct mesg_buffer {
long msg_type;
char msg_text[100];
} message;
int main()
{
key_t key;
int msgid;
// ftok to generate unique key
key = ftok("fifo.txt", 65);
if (key == -1) {
perror("ftok failed");
exit(1);
}
// msgget creates a message queue and returns an identifier
msgid = msgget(key, 0666 | IPC_CREAT);
if (msgid == -1) {
perror("msgget failed");
exit(1);
}
message.msg_type = 1;
// Use fgets instead of gets for safer input
printf("Write Data: ");
if (fgets(message.msg_text, sizeof(message.msg_text), stdin) == NULL) {
perror("fgets failed");
exit(1);
}
// Remove trailing newline character that fgets adds
message.msg_text[strcspn(message.msg_text, "\n")] = '\0';
// msgsnd to send message
if (msgsnd(msgid, &message, sizeof(message.msg_text), 0) == -1) {
perror("msgsnd failed");
exit(1);
}
// display the message
printf("Data sent is: %s\n", message.msg_text);
return 0;
}
OUTPUT :
Message Queue (Reader Process)
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
// structure for message queue
struct mesg_buffer {
long mesg_type;
char mesg_text[100];
} message;
int main()
{
key_t key;
int msgid;
// ftok to generate unique key
key = ftok("fifo.txt", 65);
// msgget creates a message queue
// and returns identifier
msgid = msgget(key, 0666 | IPC_CREAT);
// msgrcv to receive message
msgrcv(msgid, &message, sizeof(message), 1, 0);
// display the message
printf("Data Received is : %s \n",message.mesg_text);
// to destroy the message queue
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
OUTPUT:
d) Shared Memory
Shmwrite.c
Program:
#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#define SHM_SIZE 1024 // Shared memory size
int main() {
key_t key = ftok("shmfile", 65); // Generate the same key
int shmid = shmget(key, SHM_SIZE, 0666); // Get shared memory ID
if (shmid == -1) {
perror("shmget failed");
exit(1);
}
char *shared_memory = (char *)shmat(shmid, NULL, 0); // Attach to shared memory
if (shared_memory == (char *)(-1)) {
perror("shmat failed");
exit(1);
}
printf("Message read from shared memory: %s", shared_memory);
shmdt(shared_memory); // Detach from shared memory
shmctl(shmid, IPC_RMID, NULL); // Remove shared memory
return 0;
}
OUTPUT:
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ cc shmwrite.c
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ ./a.out
Enter a message: Hi Kumar
Message written to shared memory: Hi Kumar
Shmread.c
Program:
#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#define SHM_SIZE 1024 // Shared memory size
int main() {
key_t key = ftok("shmfile", 65); // Generate the same key
int shmid = shmget(key, SHM_SIZE, 0666); // Get shared memory ID
if (shmid == -1) {
perror("shmget failed");
exit(1);
}
char *shared_memory = (char *)shmat(shmid, NULL, 0); // Attach to shared memory
if (shared_memory == (char *)(-1)) {
perror("shmat failed");
exit(1);
}
printf("Message read from shared memory: %s", shared_memory);
shmdt(shared_memory); // Detach from shared memory
shmctl(shmid, IPC_RMID, NULL); // Remove shared memory
return 0;
}
OUTPUT:
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ cc shmread.c
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ ./a.out
Message read from shared memory: Hi Kumar
6. Aim: Write C programs to simulate the following memory management techniques
a) Paging
AIM: To write a C program to implement memory management using paging technique.
ALGORITHM:
Step1 : Start the program.
Step2 : Read the base address, page size, number of pages and memory unit.
Step3 : If the memory limit is less than the base address display the memory limit is less than
limit.
Step4 : Create the page table with the number of pages and page address.
Step5 : Read the page number and displacement value.
Step6 : If the page number and displacement value is valid, add the displacement value with the
address
corresponding to the page number and display the result.
Step7 : Display the page is not found or displacement should be less than page size.
Step8 : Stop the program.
PROGRAM:
#include <stdio.h>
int main() {
int ms, ps, nop, np, rempages, i, j, x, y, pa, offset;
int s[10], fno[10][20];
printf("Enter the memory size: ");
scanf("%d", &ms);
printf("Enter the page size: ");
scanf("%d", &ps);
nop = ms / ps;
printf("The number of pages available in memory: %d\n", nop);
printf("Enter number of processes: ");
scanf("%d", &np);
rempages = nop;
for (i = 1; i <= np; i++) {
printf("Enter number of pages required for p[%d]: ", i);
scanf("%d", &s[i]);
if (s[i] > rempages) {
printf("Memory is Full\n");
break;
}
rempages -= s[i];
printf("Enter page table for p[%d] (frame numbers):\n", i);
for (j = 0; j < s[i]; j++) {
printf("Page %d -> Frame: ", j);
scanf("%d", &fno[i][j]);
}
}
printf("\nEnter Logical Address to find Physical Address\n");
printf("Enter process number, page number, and offset: ");
scanf("%d %d %d", &x, &y, &offset);
if (x > np || y >= s[x] || offset >= ps) {
printf("Invalid Process or Page Number or Offset\n");
} else {
pa = fno[x][y] * ps + offset;
printf("The Physical Address is: %d\n", pa);
}
return 0;
}
OUTPUT :
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ cc paging.c
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ ./a.out
Enter the memory size: 1000
Enter the page size: 100
The number of pages available in memory: 10
Enter number of processes: 2
Enter number of pages required for p[1]: 3
Enter page table for p[1] (frame numbers):
Page 0 -> Frame: 4
Page 1 -> Frame: 5
Page 2 -> Frame: 9
Enter number of pages required for p[2]: 2
Enter page table for p[2] (frame numbers):
Page 0 -> Frame: 3
Page 1 -> Frame: 5
Enter Logical Address to find Physical Address
Enter process number, page number, and offset: 1 1 20
The Physical Address is: 520
b) Segmentation
Aim: To write a C program to implement memory management using segmentation
Algorithm:
Step1 : Start the program.
Step2 : Read the base address, number of segments, size of each segment, memory limit.
Step3 : If memory address is less than the base address display “invalid memory limit”.
Step4 : Create the segment table with the segment number and segment address and display it.
Step5 : Read the segment number and displacement.
Step6 : If the segment number and displacement is valid compute the real address and display the
same. Step7 :
Stop the program.
PROGRAM :
#include <stdio.h>
#include <stdlib.h> // for malloc
struct list {
int seg;
int base;
int limit;
struct list *next;
} *p = NULL;
void insert(struct list **q, int base, int limit, int seg) {
struct list *temp = (struct list *)malloc(sizeof(struct list));
temp->base = base;
temp->limit = limit;
temp->seg = seg;
temp->next = NULL;
if (*q == NULL) {
*q = temp;
} else {
struct list *curr = *q;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = temp;
}
}
int find_limit(struct list *q, int seg) {
while (q != NULL) {
if (q->seg == seg)
return q->limit;
q = q->next;
}
return -1; // segment not found
}
int find_base(struct list *q, int seg) {
while (q != NULL) {
if (q->seg == seg)
return q->base;
q = q->next;
}
return -1; // segment not found
}
int main() {
int seg, offset, limit, base;
int physical;
printf("Enter segment table\n");
printf("Enter -1 as segment number to stop\n");
do {
printf("Enter segment number: ");
scanf("%d", &seg);
if (seg != -1) {
printf("Enter base value: ");
scanf("%d", &base);
printf("Enter limit value: ");
scanf("%d", &limit);
insert(&p, base, limit, seg);
}
} while (seg != -1);
printf("Enter offset: ");
scanf("%d", &offset);
printf("Enter segment number: ");
scanf("%d", &seg);
limit = find_limit(p, seg);
base = find_base(p, seg);
if (limit == -1 || base == -1) {
printf("Segment not found.\n");
} else if (offset < limit) {
physical = base + offset;
printf("Address in physical memory: %d\n", physical);
} else {
printf("Error: Offset exceeds segment limit.\n");
}
return 0;
}
OUTPUT:
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ cc segm.c
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ ./a.out
Enter segment table
Enter -1 as segment number to stop
Enter segment number: 0
Enter base value: 1000
Enter limit value: 200
Enter segment number: 1
Enter base value: 300
Enter limit value: 100
Enter segment number: -1
Enter offset: 50
Enter segment number: 0
Address in physical memory: 1050
7. Write C programs to simulate Page replacement policies a) FCFS b) LRU c) Optimal
Aim: To write C programs to simulate the following page replacement policies:
1. FCFS (First Come First Serve)
Algorithm:
● Maintain a queue of pages in memory.
● On a page fault:
○ If memory is not full, insert the page.
○ If full, remove the oldest page and insert the new one.
● Count page faults.
PROGRAM :
#include <stdio.h>
int main() {
int frames, pages[50], temp[50];
int i, j, k, pageFaults = 0, flag = 0, n;
printf("Enter number of pages: ");
scanf("%d", &n);
printf("Enter the page reference string: ");
for (i = 0; i < n; i++) {
scanf("%d", &pages[i]);
}
printf("Enter number of frames: ");
scanf("%d", &frames);
int index = 0;
for (i = 0; i < n; i++) {
flag = 0;
for (j = 0; j < frames; j++) {
if (temp[j] == pages[i]) {
flag = 1;
break;
}
}
if (flag == 0) {
temp[index] = pages[i];
index = (index + 1) % frames;
pageFaults++;
}
}
printf("Total Page Faults (FCFS): %d\n", pageFaults);
return 0;
}
OUTPUT:
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ cc fcfsp.c
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ ./a.out
Enter number of pages: 10
Enter the page reference string: 9 5 1 2 3 5 7 4 0 5
Enter number of frames: 3
Total Page Faults (FCFS): 10
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ ./a.out
Enter number of pages: 10
Enter the page reference string: 1 2 3 4 5 6 5 4 6 2
Enter number of frames: 4
Total Page Faults (FCFS): 7
2. LRU (Least Recently Used)
Algorithm:
● Maintain a list of pages with most recently used at the end.
● On a page hit, move the page to the end.
● On a page fault:
○ If memory is not full, insert the page.
○ Else, remove the least recently used page (front) and insert the new one.
● Count page faults.
PROGRAM:
#include <stdio.h>
int main() {
int pages[50], frames[10], recent[10];
int n, f, i, j, k, flag, pageFaults = 0;
printf("Enter number of pages: ");
scanf("%d", &n);
printf("Enter the page reference string: ");
for (i = 0; i < n; i++)
scanf("%d", &pages[i]);
printf("Enter number of frames: ");
scanf("%d", &f);
for (i = 0; i < f; i++) {
frames[i] = -1;
}
for (i = 0; i < n; i++) {
flag = 0;
for (j = 0; j < f; j++) {
if (frames[j] == pages[i]) {
flag = 1;
recent[j] = i;
break;
}
}
if (flag == 0) {
int min = recent[0], pos = 0;
for (j = 0; j < f; j++) {
if (frames[j] == -1) {
pos = j;
break;
}
if (recent[j] < min) {
min = recent[j];
pos = j;
}
}
frames[pos] = pages[i];
recent[pos] = i;
pageFaults++;
}
}
printf("Total Page Faults (LRU): %d\n", pageFaults);
return 0;
OUTPUT:
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ cc LRU.c
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ ./a.out
Enter number of pages: 12
Enter the page reference string: 1 4 3 2 3 5 4 6 6 7 8 9
Enter number of frames: 3
Total Page Faults (LRU): 10
3. Optimal Page Replacement
Algorithm:
● On a page fault:
○ If memory is not full, insert the page.
○ Else, look ahead in the page reference string and remove the page that won’t be
used for the longest time.
● Count page faults.
PROGRAM :
#include <stdio.h>
int main() {
int frames[10], pages[50];
int i, j, k, n, f, pageFaults = 0, flag, farthest, pos;
printf("Enter number of pages: ");
scanf("%d", &n);
printf("Enter the page reference string: ");
for (i = 0; i < n; i++) {
scanf("%d", &pages[i]);
}
printf("Enter number of frames: ");
scanf("%d", &f);
for (i = 0; i < f; i++)
frames[i] = -1;
for (i = 0; i < n; i++) {
flag = 0;
// Check if page is already in frame
for (j = 0; j < f; j++) {
if (frames[j] == pages[i]) {
flag = 1;
break;
}
}
if (flag == 0) {
int found = 0;
for (j = 0; j < f; j++) {
if (frames[j] == -1) {
frames[j] = pages[i];
found = 1;
break;
}
}
if (!found) {
int idx[10];
for (j = 0; j < f; j++) {
idx[j] = -1;
for (k = i + 1; k < n; k++) {
if (frames[j] == pages[k]) {
idx[j] = k;
break;
}
}
}
farthest = -1;
pos = -1;
for (j = 0; j < f; j++) {
if (idx[j] == -1) {
pos = j;
break;
}
if (idx[j] > farthest) {
farthest = idx[j];
pos = j;
}
}
frames[pos] = pages[i];
}
pageFaults++;
}
}
printf("Total Page Faults (Optimal): %d\n", pageFaults);
return 0;
OUTPUT:
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ cc optimal.c
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ ./a.out
Enter number of pages: 10
Enter the page reference string: 1 2 3 4 5 6 4 5 2
Enter number of frames: 3
Total Page Faults (Optimal): 7