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

microooooo

The document provides C programs for implementing the Producer-Consumer problem using semaphores and various IPC mechanisms such as pipes, message queues, and shared memory. It includes algorithms and program structures for memory management techniques like paging and segmentation. The programs demonstrate the use of UNIX/Linux system calls for inter-process communication and memory management in C.

Uploaded by

ghullesangamesh
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)
11 views

microooooo

The document provides C programs for implementing the Producer-Consumer problem using semaphores and various IPC mechanisms such as pipes, message queues, and shared memory. It includes algorithms and program structures for memory management techniques like paging and segmentation. The programs demonstrate the use of UNIX/Linux system calls for inter-process communication and memory management in C.

Uploaded by

ghullesangamesh
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/ 5

WEEK-4 { void consumer ()

{
Write a C program to implement the Producer-Consumer problem using semaphores using case 1: mutex = wait (mutex);
UNIX/LINUX system calls. if ((mutex == 1) && (empty != 0)) full = wait (full);
Aim: producer (); empty = signal (empty);
Write a C program to implement the Producer-Consumer problem using semaphores using else printf ("\nConsumer consumes item %d", x);
UNIX/LINUX system calls. printf ("Buffer is full!!"); x--;
Algorithm: break; mutex = signal (mutex);
1. The Semaphore mutex, full & empty is initialized. }
2. In the case of producer process case 2:
3. Produce an item in a temporary variable. if ((mutex == 1) && (full != 0)) Output:
If there is empty space in the buffer check the mutex value to enter into the critical section. consumer ();
If the mutex value is 0, allow the producer to add value in the temporary variable to the else
buffer. printf ("Buffer is empty!!");
4. In the case of consumer process break;
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 case 3:
item from buffer exit (0);
iii) Signal the mutex value and reduce the empty value by 1. break;
iv) Consume the item. }
5. Print the result }
return 0;
Program: }
int wait (int s)
#include<stdio.h> {
#include<stdlib.h> return (--s);
int mutex = 1, full = 0, empty = 3, x = 0; }
int main () int signal (int s)
{ {
int n; return (++s);
void producer (); }
void consumer (); void producer ()
int wait (int); {
int signal (int); mutex = wait (mutex);
printf ("\n1.Producer\n2.Consumer\n3.Exit"); full = signal (full);
while (1) empty = wait (empty);
{ x++;
printf ("\nEnter your choice:"); printf ("\nProducer produces the item %d", x);
scanf ("%d", &n); mutex = signal (mutex);
switch (n) }

Week: 5 ​ }
Write C programs to illustrate the following IPC mechanisms ​ // Write first message to the pipe
​ strncpy(message, "Kumar Chinthala,", MSG_LEN - 1); ​ // Close the write end of the pipe after writing all messages
Aim: Write C programs to illustrate the following IPC mechanisms ​ message[MSG_LEN - 1] = '\0'; // Ensure null termination ​ close(fd[1]);
​ result = write(fd[1], message, strlen(message));
ALGORITHM:
1. Start the program. ​ if (result < 0) { ​ // Read from the pipe
2. Declare the variables. ​ perror("write"); ​ result = read(fd[0], recvd_msg, MSG_LEN - 1);
3. Read the choice. ​ exit(2); ​ if (result < 0) {
4. Create a piping processing using IPC. ​ } ​ perror("read");
5. Assign the variable lengths ​ exit(3);
6. “strcpy” the message lengths.
​ // Write second message to the pipe ​ }
7. To join the operation using IPC .
8. Stop the program ​ strncpy(message, "CSE-DS,", MSG_LEN - 1); ​ recvd_msg[result] = '\0'; // Null terminate the received message
​ message[MSG_LEN - 1] = '\0'; // Ensure null termination
​ result = write(fd[1], message, strlen(message)); ​ // Print the received message
Program : ​ if (result < 0) { ​ printf("Received message: %s\n", recvd_msg);
​ perror("write");
#include <unistd.h> ​ exit(2); ​ return 0;
#include <stdlib.h> ​ } }
#include <stdio.h>
#include <string.h> ​ // Write third message to the pipe Output:
​ strncpy(message, "MRCE,", MSG_LEN - 1);
#define MSG_LEN 64 ​ message[MSG_LEN - 1] = '\0'; // Ensure null termination
​ result = write(fd[1], message, strlen(message));
int main() { ​ if (result < 0) {
​ int result; ​ perror("write");
​ int fd[2]; ​ exit(2);
​ char message[MSG_LEN]; ​ }
​ char recvd_msg[MSG_LEN];
​ // Write fourth message to the pipe
​ // Creating the pipe ​ strncpy(message, "Hyderabad", MSG_LEN - 1);
​ result = pipe(fd); ​ message[MSG_LEN - 1] = '\0'; // Ensure null termination
​ if (result < 0) { ​ result = write(fd[1], message, strlen(message));
​ perror("pipe"); ​ if (result < 0) {
​ exit(1); ​ perror("write");
​ } ​ exit(2);
a)​ FIFO C) Message Queue (Writer Process) ​ // Use fgets instead of gets for safer input
​ printf("Write Data: ");
Program: #include <stdio.h> ​ if (fgets(message.msg_text, sizeof(message.msg_text), stdin) == NULL) {
#include <stdio.h> #include <stdlib.h> ​ perror("fgets failed");
#include <stdlib.h> #include <string.h> ​ exit(1);
#include <sys/stat.h> #include <sys/ipc.h> ​ }
#include <unistd.h> #include <sys/msg.h>
#include <linux/stat.h> ​ // Remove trailing newline character that fgets adds
#define FIFO_FILE "fifo.txt" // structure for message queue ​ message.msg_text[strcspn(message.msg_text, "\n")] = '\0';
int main(void) struct mesg_buffer {
{ ​ long msg_type; ​ // msgsnd to send message
FILE *fp; ​ char msg_text[100]; ​ if (msgsnd(msgid, &message, sizeof(message.msg_text), 0) == -1) {
char readbuf[80]; } message; ​ perror("msgsnd failed");
/* Create the FIFO if it does not exist */ ​ exit(1);
umask(0); int main() ​ }
mknod(FIFO_FILE, S_IFIFO|0666, 0); {
while(1) ​ key_t key; ​ // display the message
{ ​ int msgid; ​ printf("Data sent is: %s\n", message.msg_text);
fp = fopen(FIFO_FILE, "r");
fgets(readbuf, 80, fp); ​ // ftok to generate unique key ​ return 0;
printf("Received string: %s \n", readbuf); ​ key = ftok("fifo.txt", 65); }
fclose(fp); ​ if (key == -1) {
} ​ perror("ftok failed"); OUTPUT :
return(0); ​ exit(1);
} ​ }

OUTPUT: ​ // 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;

Message Queue (Reader Process) d) Shared Memory OUTPUT:


mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ cc shmwrite.c
Shmwrite.c mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ ./a.out
#include <stdio.h>
Enter a message: Hi Kumar
#include <sys/ipc.h> Program: Message written to shared memory: Hi Kumar
#include <sys/msg.h>
// structure for message queue #include <stdio.h>
struct mesg_buffer { #include <stdlib.h>
long mesg_type; #include <sys/shm.h>
#include <sys/ipc.h>
char mesg_text[100];
} message; #define SHM_SIZE 1024 // Shared memory size
int main()
{ int main() {
key_t key; ​ key_t key = ftok("shmfile", 65); // Generate the same key
int msgid; ​ int shmid = shmget(key, SHM_SIZE, 0666); // Get shared memory ID
// ftok to generate unique key
​ if (shmid == -1) {
key = ftok("fifo.txt", 65); ​ perror("shmget failed");
// msgget creates a message queue ​ exit(1);
// and returns identifier ​ }
msgid = msgget(key, 0666 | IPC_CREAT);
// msgrcv to receive message ​ char *shared_memory = (char *)shmat(shmid, NULL, 0); // Attach to shared memory
msgrcv(msgid, &message, sizeof(message), 1, 0);
​ if (shared_memory == (char *)(-1)) {
// display the message ​ perror("shmat failed");
printf("Data Received is : %s \n",message.mesg_text); ​ exit(1);
// to destroy the message queue ​ }
msgctl(msgid, IPC_RMID, NULL);
return 0; ​ printf("Message read from shared memory: %s", shared_memory);
}
​ shmdt(shared_memory); // Detach from shared memory
OUTPUT:
​ shmctl(shmid, IPC_RMID, NULL); // Remove shared memory

​ return 0;
}
6. Aim: Write C programs to simulate the following memory management techniques ​ printf("Enter number of pages required for p[%d]: ", i);
Shmread.c ​ scanf("%d", &s[i]);
a) Paging
Program: AIM: To write a C program to implement memory management using paging technique. ​ if (s[i] > rempages) {
ALGORITHM: ​ printf("Memory is Full\n");
#include <stdio.h> Step1 : Start the program. ​ break;
#include <stdlib.h> Step2 : Read the base address, page size, number of pages and memory unit. ​ }
#include <sys/shm.h> Step3 : If the memory limit is less than the base address display the memory limit is less than
#include <sys/ipc.h> limit. ​ rempages -= s[i];
Step4 : Create the page table with the number of pages and page address. ​ printf("Enter page table for p[%d] (frame numbers):\n", i);
#define SHM_SIZE 1024 // Shared memory size Step5 : Read the page number and displacement value. ​ for (j = 0; j < s[i]; j++) {
Step6 : If the page number and displacement value is valid, add the displacement value with the ​ printf("Page %d -> Frame: ", j);
int main() { address ​ scanf("%d", &fno[i][j]);
​ key_t key = ftok("shmfile", 65); // Generate the same key corresponding to the page number and display the result. ​ }
​ int shmid = shmget(key, SHM_SIZE, 0666); // Get shared memory ID Step7 : Display the page is not found or displacement should be less than page size. ​ }
Step8 : Stop the program.
​ if (shmid == -1) { ​ printf("\nEnter Logical Address to find Physical Address\n");
​ perror("shmget failed"); PROGRAM: ​ printf("Enter process number, page number, and offset: ");
​ exit(1); ​ scanf("%d %d %d", &x, &y, &offset);
​ } #include <stdio.h>
​ if (x > np || y >= s[x] || offset >= ps) {
​ char *shared_memory = (char *)shmat(shmid, NULL, 0); // Attach to shared memory int main() { ​ printf("Invalid Process or Page Number or Offset\n");
​ int ms, ps, nop, np, rempages, i, j, x, y, pa, offset; ​ } else {
​ if (shared_memory == (char *)(-1)) { ​ int s[10], fno[10][20]; ​ pa = fno[x][y] * ps + offset;
​ perror("shmat failed"); ​ printf("The Physical Address is: %d\n", pa);
​ exit(1); ​ printf("Enter the memory size: "); ​ }
​ } ​ scanf("%d", &ms);
​ return 0;
​ printf("Message read from shared memory: %s", shared_memory); ​ printf("Enter the page size: "); }
​ scanf("%d", &ps);
​ shmdt(shared_memory); // Detach from shared memory OUTPUT :
​ nop = ms / ps;
​ shmctl(shmid, IPC_RMID, NULL); // Remove shared memory ​ printf("The number of pages available in memory: %d\n", nop); mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ cc paging.c
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ ./a.out
​ return 0; ​ printf("Enter number of processes: "); Enter the memory size: 1000
} ​ scanf("%d", &np); Enter the page size: 100
OUTPUT: The number of pages available in memory: 10
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ cc shmread.c ​ rempages = nop; Enter number of processes: 2
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ ./a.out Enter number of pages required for p[1]: 3
Message read from shared memory: Hi Kumar ​ for (i = 1; i <= np; i++) { Enter page table for p[1] (frame numbers):

Page 0 -> Frame: 4 b) Segmentation ​ curr->next = temp;


Page 1 -> Frame: 5 ​ }
Page 2 -> Frame: 9 Aim: To write a C program to implement memory management using segmentation }
Enter number of pages required for p[2]: 2 Algorithm:
Enter page table for p[2] (frame numbers): Step1 : Start the program. int find_limit(struct list *q, int seg) {
Page 0 -> Frame: 3 Step2 : Read the base address, number of segments, size of each segment, memory limit. ​ while (q != NULL) {
Page 1 -> Frame: 5 Step3 : If memory address is less than the base address display “invalid memory limit”. ​ if (q->seg == seg)
Step4 : Create the segment table with the segment number and segment address and display it. ​ return q->limit;
Enter Logical Address to find Physical Address Step5 : Read the segment number and displacement. ​ q = q->next;
Enter process number, page number, and offset: 1 1 20 Step6 : If the segment number and displacement is valid compute the real address and display the ​ }
The Physical Address is: 520 same. Step7 : ​ return -1; // segment not found
Stop the program. }

int find_base(struct list *q, int seg) {


PROGRAM : ​ while (q != NULL) {
​ if (q->seg == seg)
#include <stdio.h> ​ return q->base;
#include <stdlib.h> // for malloc ​ q = q->next;
​ }
struct list { ​ return -1; // segment not found
​ int seg; }
​ int base;
​ int limit; int main() {
​ struct list *next; ​ int seg, offset, limit, base;
} *p = NULL; ​ int physical;

void insert(struct list **q, int base, int limit, int seg) { ​ printf("Enter segment table\n");
​ struct list *temp = (struct list *)malloc(sizeof(struct list)); ​ printf("Enter -1 as segment number to stop\n");
​ temp->base = base;
​ temp->limit = limit; ​ do {
​ temp->seg = seg; ​ printf("Enter segment number: ");
​ temp->next = NULL; ​ scanf("%d", &seg);
​ if (seg != -1) {
​ if (*q == NULL) { ​ printf("Enter base value: ");
​ *q = temp; ​ scanf("%d", &base);
​ } else { ​ printf("Enter limit value: ");
​ struct list *curr = *q; ​ scanf("%d", &limit);
​ while (curr->next != NULL) { ​ insert(&p, base, limit, seg);
​ curr = curr->next; ​ }
​ } ​ } while (seg != -1);
7. Write C programs to simulate Page replacement policies a) FCFS b) LRU c) Optimal ​ scanf("%d", &frames);
​ printf("Enter offset: ");
​ scanf("%d", &offset); Aim: To write C programs to simulate the following page replacement policies:
​ printf("Enter segment number: ");
1.​ FCFS (First Come First Serve)​ ​ int index = 0;
​ scanf("%d", &seg);
Algorithm:
​ for (i = 0; i < n; i++) {
​ limit = find_limit(p, seg); ●​ Maintain a queue of pages in memory.​
​ base = find_base(p, seg); ​ flag = 0;
●​ On a page fault:​
​ if (limit == -1 || base == -1) {
​ printf("Segment not found.\n"); ○​ If memory is not full, insert the page.​
​ for (j = 0; j < frames; j++) {
​ } else if (offset < limit) {
​ physical = base + offset; ○​ If full, remove the oldest page and insert the new one.​
​ if (temp[j] == pages[i]) {
​ printf("Address in physical memory: %d\n", physical);
​ } else { ●​ Count page faults. ​ flag = 1;
​ printf("Error: Offset exceeds segment limit.\n");
PROGRAM : ​ break;
​ }
#include <stdio.h> ​ }
​ return 0;
} ​ }

OUTPUT: int main() {

mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ cc segm.c ​ int frames, pages[50], temp[50]; ​ if (flag == 0) {


mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ ./a.out
​ int i, j, k, pageFaults = 0, flag = 0, n; ​ temp[index] = pages[i];
Enter segment table
Enter -1 as segment number to stop ​ index = (index + 1) % frames;
Enter segment number: 0
Enter base value: 1000 ​ printf("Enter number of pages: "); ​ pageFaults++;
Enter limit value: 200
Enter segment number: 1 ​ scanf("%d", &n); ​ }
Enter base value: 300
​ printf("Enter the page reference string: "); ​ }
Enter limit value: 100
Enter segment number: -1 ​ for (i = 0; i < n; i++) {
Enter offset: 50
Enter segment number: 0 ​ scanf("%d", &pages[i]); ​ printf("Total Page Faults (FCFS): %d\n", pageFaults);
Address in physical memory: 1050
​ } ​ return 0;

​ printf("Enter number of frames: "); }

2.​ LRU (Least Recently Used)

OUTPUT: Algorithm: ​ for (i = 0; i < f; i++) {

●​ Maintain a list of pages with most recently used at the end.​ ​ frames[i] = -1;

mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ cc fcfsp.c ●​ On a page hit, move the page to the end.​ ​ }

mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ ./a.out
●​ On a page fault:​
Enter number of pages: 10 ​ for (i = 0; i < n; i++) {
○​ If memory is not full, insert the page.​
Enter the page reference string: 9 5 1 2 3 5 7 4 0 5 ​ flag = 0;
○​ Else, remove the least recently used page (front) and insert the new one.​
Enter number of frames: 3 ​ for (j = 0; j < f; j++) {
●​ Count page faults.
Total Page Faults (FCFS): 10 ​ if (frames[j] == pages[i]) {
PROGRAM:
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ ./a.out ​ flag = 1;
#include <stdio.h>
Enter number of pages: 10 ​ recent[j] = i;

Enter the page reference string: 1 2 3 4 5 6 5 4 6 2 ​ break;


int main() {
Enter number of frames: 4 ​ }
​ int pages[50], frames[10], recent[10];
Total Page Faults (FCFS): 7 ​ }
​ int n, f, i, j, k, flag, pageFaults = 0;

​ if (flag == 0) {
​ printf("Enter number of pages: ");
​ int min = recent[0], pos = 0;
​ scanf("%d", &n);
​ for (j = 0; j < f; j++) {
​ printf("Enter the page reference string: ");
​ if (frames[j] == -1) {
​ for (i = 0; i < n; i++)
​ pos = j;
​ scanf("%d", &pages[i]);
​ break;

​ }
​ printf("Enter number of frames: ");
​ if (recent[j] < min) {
​ scanf("%d", &f);
​ min = recent[j]; ​ }

​ pos = j; ​

​ } ​ printf("Enter number of frames: ");

​ } ​ scanf("%d", &f);

​ frames[pos] = pages[i];

​ recent[pos] = i; ​ for (i = 0; i < f; i++)


3.​ Optimal Page Replacement
​ pageFaults++; ​ frames[i] = -1;
Algorithm:
​ }
●​ On a page fault:​
​ } ​ for (i = 0; i < n; i++) {
○​ If memory is not full, insert the page.​
​ flag = 0;

​ printf("Total Page Faults (LRU): %d\n", pageFaults); ○​ Else, look ahead in the page reference string and remove the page that won’t be
used for the longest time.​
​ return 0; ​ // Check if page is already in frame
●​ Count page faults.
} ​ for (j = 0; j < f; j++) {
PROGRAM :
​ if (frames[j] == pages[i]) {
#include <stdio.h>
OUTPUT: ​ flag = 1;
int main() {
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ cc LRU.c ​ break;
​ int frames[10], pages[50];
mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ ./a.out ​ }
​ int i, j, k, n, f, pageFaults = 0, flag, farthest, pos;
Enter number of pages: 12 ​ }

Enter the page reference string: 1 4 3 2 3 5 4 6 6 7 8 9


​ printf("Enter number of pages: ");
Enter number of frames: 3 ​ if (flag == 0) {
​ scanf("%d", &n);
Total Page Faults (LRU): 10 ​ int found = 0;
​ printf("Enter the page reference string: ");
​ for (j = 0; j < f; j++) {
​ for (i = 0; i < n; i++) {
​ if (frames[j] == -1) {
​ scanf("%d", &pages[i]);

​ frames[j] = pages[i]; ​ break; Enter the page reference string: 1 2 3 4 5 6 4 5 2

​ found = 1; ​ } 6

​ break; ​ if (idx[j] > farthest) { Enter number of frames: 3

​ } ​ farthest = idx[j]; Total Page Faults (Optimal): 7

​ } ​ pos = j;

​ }

​ if (!found) { ​ }

​ int idx[10];

​ for (j = 0; j < f; j++) { ​ frames[pos] = pages[i];

​ idx[j] = -1; ​ }

​ for (k = i + 1; k < n; k++) {

​ if (frames[j] == pages[k]) { ​ pageFaults++;

​ idx[j] = k; ​ }

​ break; ​ }

​ }

​ } ​ printf("Total Page Faults (Optimal): %d\n", pageFaults);

​ } ​ return 0;

​ farthest = -1;

​ pos = -1; OUTPUT:

​ for (j = 0; j < f; j++) { mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ cc optimal.c

​ if (idx[j] == -1) { mrce@mrce-ThinkCentre-neo-50s-Gen-4:~$ ./a.out

​ pos = j; Enter number of pages: 10

You might also like