Forgive me for not using quote, bold and code format due to technical limitation in my system.
I am learning shared memory.I written two file
In 1stfile I am creating segments and writing a string on segment
In second file I am trying to read that shared memory data and trying to print the string.
Error I am getting is segmentation fault while running 2nd file .
Please guide me in this
/* 1st program:shared.c*/
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 2048 /* make it a 2K shared memory segment */
int main()
{
key_t key;
int shmid;
char *data;
if ((key = ftok("p.c", 'R')) == -1) {
perror("ftok");
exit(1);
}
if ((shmid = shmget(key, SHM_SIZE, IPC_CREAT )) == -1) {
perror("shmget");
exit(1);
}
printf("shmid = %d\n", shmid);
data = shmat(shmid, 0, 0);
if (data == (char *)(-1)) {
perror("shmat");
exit(1);
}
printf("Enter A String:");
gets(data);
printf("\nString %s\n", data);
printf("Address %u\n",data);
printf("Integer val %u",data);
if (shmdt(data) == -1) {
perror("shmdt");
exit(1);
}
/* 2nd program
ro.c*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
int main()
{
key_t key;
char *data;
int shmid;
key = ftok("p.c",'T');
shmid = shmget(key, 2048, IPC_EXCL);
printf("shmid = %d\n", shmid);
printf("key = %ld\n", key);
data =(char *)shmat(shmid,0,0);
printf("Entered Shared Memory Data: %u",data);
printf("Entered Shared Memory Data: %s",data);
return 0;
}