![]() |
| | #1 |
| Registered User Join Date: Apr 2009
Posts: 13
| Help with shared memory and semaphores My problem is that while the course teaches us the theory behind these structures I have been given nothing on how to implement these in C. I have been looking at a number of different places on the web trying to wrap my head around how to use these in C but I am still having major issues. I am asking if anyone could point me to some reference materials that clearly and simply outline how to create shared memory, semaphores, mutex's, circular buffers etc. preferably using pthreads thank you Michael |
| strider1974 is offline | |
| | #2 |
| pwning noobs Join Date: Jun 2009 Location: The Great White North
Posts: 125
| Hello strider. I assume you're using linux and that the system V interprocess communication (IPC) mechanism are OK to use. You could also use posix shared memory and posix semaphores. You don't really need shared memory or semaphores if the producer and consumer are threads in the same process (as you imply), but I understand that it may be a requirement for your assignment. The functions you're looking for are shmget, shmat, and shmdt for shared memory. You can read the man pages for them. Here is a simple example of creating shared memory. Code:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <fcntl.h>
typedef struct
{
int x;
} WorkUnit;
WorkUnit* pShm;
int main(void)
{
int shmid;
pid_t child;
key_t key = 0x1234;
// Or use ftok function
if ((shmid = shmget(key, sizeof(WorkUnit)*10, IPC_CREAT | 0666)) < 0)
{
perror("shmget");
return 1;
}
if ((pShm = (WorkUnit*)shmat(shmid, NULL, 0)) == (void*)-1)
{
perror("shmat");
return -1;
}
/* Do some work then detach from shared memory */
shmdt((void*)pShm);
return 0;
I hope that starts you off. You really need to specify more information about your problem.
__________________ Sun Certified Java Programmer / Developer IEEE CSDP |
| Zlatko is offline | |
| | #3 |
| Registered User Join Date: Apr 2009
Posts: 13
| Zlato cheers, this got headed in the right direction even though my post was lacking in details Sorry for the late reply it has been a hell of week |
| strider1974 is offline | |
![]() |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Shared Memory semaphores? | Ironic | C Programming | 0 | 10-31-2008 07:13 PM |
| problem with sending array of struct over shared memory | jet-plane | C Programming | 26 | 05-10-2008 04:10 AM |
| shared memory & mutex | lollobrigido | Linux Programming | 3 | 02-22-2008 04:34 PM |
| reader/writer locks on shared mem using semaphores | gibsosmat | C Programming | 15 | 11-21-2007 11:47 PM |
| Managing shared memory lookups | clancyPC | Linux Programming | 0 | 10-08-2003 04:44 AM |