0% found this document useful (0 votes)
11 views4 pages

ASS7

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views4 pages

ASS7

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

ASSIGNMENT:-7

CLIENT.C Program

#include <stdio.h>

#include <stdlib.h>

#include <sys/ipc.h>

#include <sys/shm.h>

#include <string.h>

#define SHM_SIZE 1024 // Size of shared memory segment

#define SHM_KEY 1234 // Key for the shared memory segment

int main() {

int shmid;

char *shm_ptr;

// Get the shared memory segment

shmid = shmget(SHM_KEY, SHM_SIZE, 0666);

if (shmid < 0) {

perror("shmget failed");

exit(1);

// Attach to the shared memory segment

shm_ptr = shmat(shmid, NULL, 0);

if (shm_ptr == (char *)-1) {

perror("shmat failed");

exit(1);

// Wait for the message to be ready

while (shm_ptr[SHM_SIZE - 1] != 1) {

// Busy wait

// Read the message from shared memory


printf("Client: Message read from shared memory: %s\n", shm_ptr);

// Clear the flag to notify server

shm_ptr[SHM_SIZE - 1] = 0; // Set flag to 0 to indicate read

// Detach from the shared memory segment

shmdt(shm_ptr);

return 0;

SERVER.c

#include <stdio.h>

#include <stdlib.h>

#include <sys/ipc.h>

#include <sys/shm.h>

#include <string.h>

#include <unistd.h>

#define SHM_SIZE 1024 // Size of shared memory segment

#define SHM_KEY 1234 // Key for the shared memory segment

int main() {

int shmid;

char *shm_ptr;

// Create shared memory segment

shmid = shmget(SHM_KEY, SHM_SIZE, IPC_CREAT | 0666);

if (shmid < 0) {

perror("shmget failed");

exit(1);

}
// Attach to the shared memory segment

shm_ptr = shmat(shmid, NULL, 0);

if (shm_ptr == (char *)-1) {

perror("shmat failed");

exit(1);

// Write a message to shared memory

const char *message = "Hello from the server!";

strncpy(shm_ptr, message, SHM_SIZE);

// Set a flag to indicate the message is ready

shm_ptr[SHM_SIZE - 1] = 1; // Last byte as a flag

printf("Server: Message written to shared memory: %s\n", shm_ptr);

// Wait for the client to read the message

while (shm_ptr[SHM_SIZE - 1] == 1) {

sleep(1); // Sleep to avoid busy waiting

printf("Server: Client has read the message.\n");

// Cleanup

shmdt(shm_ptr);

shmctl(shmid, IPC_RMID, NULL);

return 0;

}
OUTPUT:-

You might also like