The first shmat in my program cannot fetch the start address of the shared memory.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main(int argc,char *argv[]) {
int pid;
key_t mykey;
int shmid;
long *shm;
long *shm2;
mykey=ftok("file.txt",1);
if (mykey==-1) {
perror("ftok error.\n");
return 5;
}
shmid=shmget(mykey,4,IPC_CREAT);
if (shmid==-1) {
perror("shmget error.\n");
return 5;
}
shm=(long *)shmat(shmid,NULL,SHM_RND); //error occured here
if (shm==(void *)-1) {
perror("first shmat fail.\n");
return 5;
}
(*shm)=30;
shm2=(long *)shmat(shmid,NULL,SHM_RND);
printf("%d\n",(*shm2));
return 0;
}
Is there something wrong with my code?
Thanks.