Practical 6-7
Practical 6-7
Aim: Developing Applications using Inter Process communication (using shared memory
and pipes)
Shared memory allows multiple processes to access the same region of memory. This is one
of the fastest methods of IPC, as it eliminates the need for copying data between processes.
Program Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
struct shared_data {
int num1;
int num2;
int sum;
};
int main() {
int shm_id;
if (shm_id == -1) {
perror("shmget failed");
exit(1);
perror("shmat failed");
exit(1);
shm_ptr->num1 = 10;
shm_ptr->num2 = 20;
shmdt(shm_ptr);
if (fork() == 0) {
perror("shmat failed");
exit(1);
shm_ptr->num2, shm_ptr->sum);
shmdt(shm_ptr);
return 0;
Pipes allow data to flow between processes in a unidirectional manner. One process writes to
the pipe, and the other process reads from it. Pipes can be used for communication between
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
pid_t child_pid;
char buffer[100];
// Create a pipe
if (pipe(pipe_fd) == -1) {
perror("pipe failed");
exit(1);
perror("fork failed");
exit(1);
if (child_pid == 0) {
} else {
return 0;
}
Practical 7
Aim: Simulate the Producer-Consumer problem using semaphores (using UNIX system
calls).
Program Code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define MAX_ITEMS 5
#define BUFFER_SIZE 5
// Shared buffer
int buffer[BUFFER_SIZE];
int in = 0, out = 0;
int item;
while (1) {
sem_wait(&empty);
sem_wait(&mutex);
buffer[in] = item;
in = (in + 1) % BUFFER_SIZE;
sem_post(&full);
sleep(1);
int item;
while (1) {
sem_wait(&full);
sem_wait(&mutex);
item = buffer[out];
sem_post(&mutex);
sem_post(&empty);
sleep(1);
int main() {
// Initialize semaphores
// Wait for the threads to finish (although they run forever in this example)
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
sem_destroy(&empty);
sem_destroy(&full);
sem_destroy(&mutex);
return 0;