The following code always returns -1
for creating shared memory. I don't know the reason for it. As far as I know my code is correct. Perror returns not such file or directory
. I don't know what it is pointing to, but this file and the header are in the same directory. Here is the code:
#include "MyShared.h"
int main()
{
struct MyShared *obj;
int shmid,i,childpid;
shmid=shmget(MySharedKey,sizeof(struct MyShared),PERM);
if(shmid==-1)
printf("Failed to create shared mem\n");
obj=(struct MyShared*)shmat(shmid,NULL,0);
obj->ReadFromBuf=0;
....
}
Here is the header file. My Shared.h
#ifndef MYSHARED_H_INCLUDED
#define MYSHARED_H_INCLUDED
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#define PERM (S_IRWXU | S_IRGRP)
#define MySharedKey 564732
#define SIZE 512 // 512 bytes
struct MyShared
{
char buf[SIZE];
int ReadFromBuf,WriteToBuf,readbytes;
};
#endif
Why can't this code create a shared memory?
I am using ubuntu 10.04.
I am following Unix System programming by Stevens
and it doesn't say anything or creation permissions for a shared memory.
Regards