Quote:
Originally Posted by cavemandave
hi people i have been teaching myself C for the last few months and have recently moved onto ICP shared memory. I have with aid developed some simple code that prints out some chars i then wanted to do the same with int but cannont seem to get it to work.
producer
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#define SHMSZ 27
int main()
{
int c;
int shmid;
key_t key;
int *shm, *s;
key = 5678;
if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) {
perror("shmget");
return(1);
}
if ((shm = shmat(shmid, NULL, 0)) == (int *) -1) {
perror("shmat");
return(1);
}
s = shm;
for (c = 10; c <= 20; c++)
*s++ = c;
*s = -1;
while (*shm != '*')
sleep(1);
return(0);
}
consumer
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#define SHMSZ 27
int main()
{
int shmid;
key_t key;
char *shm, *s;
key = 5678;
if ((shmid = shmget(key, SHMSZ, 0666)) < 0) {
perror("shmget");
return(1);
}
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
return(1);
}
for (s = shm; *s != 0; s++)
putchar(*s);
putchar('\n');
*shm = '*';
return(0);
}
-------------------------------------------
Hi cavemandave,
I have also worked on Shared Memory. I diagonised the following problems in your code :-
1. shmat() returns a pointer to void. So variable "shm" must be of type void pointer. But you declared it as char*.
2. When a new segment is created, the contents of the segment are initialized with zeros. (relate this point to point 3).
3. The shared memory IPC Mechanism does not have any automatic means of synchronisation for processes which are communicating. The programmer needs to implement the synchronisation at its own. And that is why when before your producer program makes the data of shared memory to some non zero value, the consumer process might be reading it before that.
If you need, then I can post the running version of your program. Feel free to mail me if any more help is still needed.
Regards,
Raj Kumar Arora