![]() |
|
|
google unix.com
|
|||||||
| Forums | Register | Forum Rules | Links | Albums | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
| UNIX for Dummies Questions & Answers If you're not sure where to post a UNIX or Linux question, post it here. All UNIX and Linux newbies welcome !! |
More UNIX and Linux Forum Topics You Might Find Helpful
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Shared memory in shared library | DreamWarrior | High Level Programming | 12 | 05-30-2007 05:33 PM |
| memory sharing - not shared memory - | elzalem | High Level Programming | 9 | 05-02-2007 08:45 AM |
| help with shared memory | ddx08 | High Level Programming | 6 | 04-06-2007 10:53 AM |
| implement shared memory | vijaya2006 | High Level Programming | 3 | 03-01-2006 05:32 PM |
| Shared memory shortage but lots of unused memory | cjcamaro | UNIX for Advanced & Expert Users | 1 | 10-13-2004 06:10 PM |
|
|
LinkBack | Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
||||
|
Trying to implement shared memory
Hi all, I'm trying to test my concepts of how shared memory works and how to access it.
So I've got a basic program that sets up a structure and shared memory segment and then tries to write / read to the shared memory segment from two different processes by doing a fork... This is my code: #include <sys/types.h> #include <sys/mman.h> #include <fcntl.h> #include <stdio.h> #include <unistd.h> #include <errno.h> #include <semaphore.h> struct shared { pid_t sh_pid; }; int main (void) { struct shared *shmPtr; size_t size = 14336; pid_t pid; int shm_fd; sem_t mutex; sem_init(&mutex, 0, 1); shm_fd = shm_open("/shared.seg", O_CREAT|O_EXCL, size); shmPtr = mmap (NULL, 14336, PROT_READ|PROT_WRITE, MAP_SHARED, shm_fd, (off_t) 0 ); if ( (pid = fork()) < 0 ) { printf("PID ERROR"); //CATCH ERROR HERE AND EXIT } else if ( pid > 0 ) { sem_wait (&mutex); printf("Inside parent semaphore\n"); //SEGMENTATION FAULT OCCURS HERE!! int display_pid = shmPtr->sh_pid; printf("pid is: %d\n", display_pid); sem_post (&mutex); } else { sem_wait(&mutex); printf("Inside child semaphore.\n"); shmPtr->sh_pid = pid; sem_post(&mutex); } shm_unlink("/shared.seg"); return 0; } So it looks like I can store some data into the shared memory segment but when I try to retrieve it I'm getting a segmentation fault. I'm guessing that I'm incorrectly calling the shared memory segment but I can't figure out what I'm doing wrong, anyone able to point me in the right direction? |
| Bookmarks |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|