Error in Communication between two process using shared memory
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:pro.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; } |
Forgive me for not reading posts whose poster didn't use [code] and [/code] tags.
|
Quote:
|
I got solved this error by hard coding the key directly in 1st argument of shmget.
Actually ftok was generating different key in different program.Hence segmentation fault @Nevem Teve.I will stick to rules here after. @psionl0. Normally I just highlight the text and select tag using mouse. Thanks you for helping me out that we can do in keyboard. |
As a start:
1. Use these compiler options: -g -W -Wall -Wextra -pedantic -Werror 2. At shmget (first program): Code:
old: if ((shmid = shmget(key, SHM_SIZE, IPC_CREAT )) == -1) { Code:
old: shmid = shmget(key, 2048, IPC_EXCL); 4. At ftok (second program): Code:
old: key = ftok("p.c",'T'); |
All times are GMT -5. The time now is 11:47 PM. |