POSIX shared memory
Just have a try with the examples provided by Operating System Concepts, P103, with some modification.
Run sm_alloc
first, and you’ll receive a shared memory segment ID.
Then run sm_write
and provide it with the ID you received just now, it will write a string Hi, shared memory!
into that memory.
Then run sm_read
and provide the ID, it will print the string in that memory.
Finally run sm_free
and provide the ID, it will free that memory.
//sm_alloc.c
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
int main()
{
int sid = 0;
int size = 4096;
sid = shmget(IPC_PRIVATE,size,S_IRUSR | S_IWUSR);
printf("%d\n",sid);
return 0;
}
//sm_write.c
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
int main()
{
int sid = 0;
scanf("%d",&sid);
char *sm = (char *)shmat(sid,NULL,0);
sprintf(sm,"Hi, shared memory!");
shmdt(sm);
return 0;
}
//sm_read.c
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
int main()
{
int sid = 0;
scanf("%d",&sid);
char *sm = (char *)shmat(sid,NULL,0);
printf("%s\n",sm);
shmdt(sm);
return 0;
}
//sm_free.c
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
int main()
{
int sid = 0;
scanf("%d",&sid);
shmctl(sid,IPC_RMID,NULL);
return 0;
}