Reputation: 4377
I am trying to create two sets of shared memory segments. One to store integers and the other one to store strings.
I keep getting an error on the second shmget
call when I am creating the shared memory segment for my integers.
keyS=5678;
keyI=6789;
//create shared memory for titles and categories
if(stringsID=shmget(keyS,sizeof(char*)*lineCounter*2,IPC_CREAT|0666)<0)
{
perror("shmget");
fprintf(stderr, "Titles Cannot create shared memory errno %i: %s\n",errno,strerror(errno));
exit(-1);
}
//attach to shared memory
if ((titlesSH = (char**)shmat(stringsID, NULL, 0)) ==(char**) -1)
{
perror("shmat");
exit(1);
}
//titles start at titlesSH[0] while categories start at titlesSH[lineCounter]
categoriesSH=titlesSH+lineCounter;
//create shared memory for stock and codes
if(intsID=shmget(keyI,sizeof(int)*lineCounter*2,IPC_CREAT|0666)<0)
{
perror("shmget");
fprintf(stderr, "Stock Cannot create shared memory errno %i: %s\n",errno,strerror(errno));
exit(-1);
}
//attach to shared memory
if((stockSH=(int*)shmat(intsID,NULL,0))==(int*)-1)
{
perror("shmat");
exit(-1);
}
When I run ipcs
in terminal I see that there are no ipcs with the keys that I am specifying in my code but I tried different keys and the result is always the same. Am I doing something wrong?
I tried removing 0666
from privileges when I am calling shmget
and it does stop (shmget
does not return -1) and let's my copy contents in but when I try to get the contents from it I get a segmentation fault.
If I remove the extra shared memory segment and keep only one everything is working fine. I know there is a workaround to this (store everything as a string in a single larger memory segment) but I also want to know why this occurs
**EDIT the workaround I noted above is currently working
I am storing all my information in a single shared memory segment that stores strings and it's size is the sum of the two segments I was trying to create. So shared memory space is not an issue. ipcs
only gives me 9 ipcs running so I suppose the limit of ipcs and the limit of space are not the issue in this case
Upvotes: 1
Views: 405
Reputation: 4503
if(stringsID=shmget(keyS,sizeof(char*)*lineCounter*2,IPC_CREAT|0666)<0)
/* and */
if(intsID=shmget(keyI,sizeof(int)*lineCounter*2,IPC_CREAT|0666)<0)
Should most probably be:
if( (stringsID=shmget(keyS,sizeof(char*)*lineCounter*2,IPC_CREAT|0666)) < 0)
/* and */
if( (intsID=shmget(keyI,sizeof(int)*lineCounter*2,IPC_CREAT|0666)) <0)
To demonstrate,
ls -ltr
ls -ltr
again#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main(void) {
int fd;
if (fd=open("omgwtf", O_RDWR|O_CREAT, 0644) < 0) {
fprintf(stderr, "WTF!\n" ); }
fprintf(stderr, "fd=%d\n", fd );
return 0;
}
Note: for extra fun, you could add O_EXCL
to the flags.
Upvotes: 1