Home > OS >  The memory. C
The memory. C

Time:10-19

#include
#include
#include
#include

1234//# define KEY KEY
# define the SIZE of 1024//to build the SIZE of the Shared memory

Int main () {
Int shmid;
Char * shmaddr;
Struct shmid_ds buf.
Shmid=shmget (KEY, the SIZE, IPC_CREAT | 0600);//set up Shared memory
If (shmid==1) {
Printf (" create share memory failed: % s ", the strerror (errno));
return 0;
}
If (the fork ()==0) {
Shmaddr=(char *) shmat (shmid, NULL, 0);//the system automatically select an address connection
If (shmaddr==(void *) - 1) {
Printf (" connect to the share memory failed: % s ", the strerror (errno));
return 0;
}
Strcpy (shmaddr, "hello, this is the child process. \n");
SHMDT (shmaddr);//disconnect with the Shared memory
return 0;
}
The else
{
Sleep (3);//wait for
the child process has been completedSHMCTL (shmid IPC_STAT, & amp; Buf);//get information about the Shared memory
Printf (" the size of the share memory: ");
Printf (" shm_segsz=% d bytes \ n ", buf. Shm_segsz);
Printf (" the process id of the creator: ");
Printf (" shm_cpid=% d \ n ", buf. Shm_cpid);
Printf (" the process id of the last operator: ");
Printf (" shm_lpid=% d \ n ", buf. Shm_lpid);
Shmaddr=(char *) shmat (shmid, NULL, 0);//the system automatically select an address connection
If (shmaddr==(void *) - 1) {
Printf (" connect to the share memory failed: % s ", the strerror (errno));
return 0;
}
Printf (" the print the content of the share memory: ");
Printf (" % s \ n ", shmaddr);
SHMDT (shmaddr);//disconnect with the Shared memory
SHMCTL (shmid IPC_RMID, NULL);
//when there is no longer any other process using the Shared memory system will automatically destroyed it
}
}
  • Related