Reputation: 75
#include<sys/shm.h>
#include<sys/stat.h>
#include<stdio.h>
int main(void)
{
int segment_id;
char *shared_memory;
const int size=4069;
segment_id=shmget(IPC_PRIVATE,size,S_IRUSR|S_IWUSR);
printf("segment ID=%d\n",segment_id);
shared_memory=(char *)shmat(segment_id,NULL,0);
sprintf(shared_memory,"Hi There!");
while(1){
}
return 0;
}
If the same segment_id entered in the input of below program, will it work?
#include<sys/shm.h>
#include<sys/stat.h>
#include<stdio.h>
int main(void)
{
int segment_id;
char *shared_memory;
const int size=4069;
printf("please input segment id\n");
scanf("%d",&segment_id);
shared_memory=(char *)shmat(segment_id,NULL,0);
printf("%s\n",shared_memory );
return 0;
}
It's working here, but please explain how it works, means how the same segment_id is working in below program also?
Upvotes: 1
Views: 282
Reputation: 7837
You are using System V shared memory, a facility provided by the operating system.
The first line of the shmget(2) manual says,
shmget() returns the identifier of the System V shared memory segment associated with the value of the argument key.
The first line of the shmat(2) manual says,
shmat() attaches the System V shared memory segment identified by shmid to the address space of the calling process.
With shmget, you provide a key and it returns an identifier. With shmat, you provide that identifier, and it returns an address you can use. What's confusing about that?
I suspect you're surprised for the same reason I was when I first encountered it. Unlike most system resources -- file descriptors, sockets, etc. -- shared memory segments aren't freed when the program terminates. They remain there, ready to be reused whenever a program provides the appropriate identifier.
You don't even need to write a program to see them. Have a look at ipcs(1) and ipcrm(1).
If you think about it, for some applications they have to be persistent. The Berkeley alternative, mmap(2), uses filenames for the same purpose.
Upvotes: 1