Linux shared memory (2)

Source: Internet
Author: User

From: http://www.cnblogs.com/hicjiajia/archive/2012/05/17/2506638.html

/* Shared memory allows two or more process processes to share the same memory (this memory is mapped to the independent address space of each process) so that these processes can communicate with each other. All processes in GNU/Linux have a unique virtual address space, and the shared memory Application Programming Interface API allows a process to use a public memory segment. However, shared access to memory also increases in complexity. The advantage of shared memory is its simplicity. When a message queue is used, a process needs to write messages to the queue, which causes a copy from the user address space to the kernel address space, the same process also needs to perform a copy when reading messages. The advantage of shared memory is that these operations are completely eliminated. The shared memory is mapped to the virtual address space of the process, which can be directly accessed by the process to avoid data replication. Therefore, shared memory is the fastest available IPC Mechanism in GNU/Linux. When a process exits, it is automatically separated from the connected shared memory segments. However, we recommend that you call shmdt to unload the shared memory segments when the process no longer uses the shared memory segments. Note: When a process is divided into Parent and Child processes, all the shared memory segments previously created by the parent process will be inherited by the quilt process. If the section has been marked for deletion (calling shmctl with a IPC--RMID command before) and the current number of connections has changed to 0, it will be removed. * // * Shmget () creates a new shared memory segment and obtains the shmctl () descriptor of the shared memory segment () get the information of a shared memory segment and set specific information for a shared memory segment. Remove a shared memory segment shmat () and attach a shared memory segment shmdt () in the separation of a shared memory segment * // create a shared memory segment and display its related information. Then, delete the shared memory partition # include <stdio. h> # include <unistd. h> // getpagesize () # include <sys/IPC. h> # include <sys/SHM. h> # define my_shm_id 67483int main () {// obtain the page size in the system printf ("page size = % d/N", getpagesize ()); // create an int shmid, RET; shmid = shmget (My_shm_id, 4096,0666 | ipc_creat); // creates a 4 kb shared memory partition. The specified size must be an integer multiple of the page size in the current system architecture // If (shmid> 0) printf ("create a shared memory segment % d/N", shmid ); // get the information of a memory segment struct shmid_ds shmds; // shmid = shmget (my_shm_id,); // example how to obtain the identifier ret = shmctl (shmid, ipc_stat, & shmds); If (ret = 0) {printf ("size of memory segment is % d/N", shmds. shm_segsz); printf ("numbre of attaches % d/N", (INT) shmds. shm_nattch);} else {printf ("shmctl () call failed/N ") ;} // Delete the shared memory partition ret = shmctl (shmid, ipc_rmid, 0); If (ret = 0) printf ("shared memory removed/N "); else printf ("Shared Memory remove failed/N"); Return 0;} // mount the shared memory segment, out of and use // understand that the shared memory segment is a large memory # include <stdio. h> # include <sys/SHM. h> # include <sys/IPC. h> # include <errno. h> # define my_shm_id 67483int main () {// mount and detach the shared memory segments from int shmid, RET; void * MEM; shmid = shmget (my_shm_id, 0, 0 ); if (shmid> = 0) {mem = sh MAT (shmid, (const void *); // shmat () returns the IF (INT) MEm pointer to the partition in the process address space! =-1) {printf ("shared memory was attached in our address space at % P/N", Mem ); // write data strcpy (char *) MEm to the shared block memory, "this is a test string. /n "); printf (" % s/n ", (char *) MEm); // detach from the shared memory segment ret = shmdt (MEM ); if (ret = 0) printf ("successfully detached memory/N"); else printf ("memory detached failed % d/N", errno );} else printf ("shmat () failed/N");} else printf ("shared memory segment not found/n "); Return 0;}/* different from the flag and message queue, a shared block can be locked. Locked segments cannot be swapped out of memory. The advantage of this is that, instead of switching the memory segment to the file system and switching back to the memory when an application is called, it is better to keep it in the memory, and visible to multiple applications. From the perspective of improving performance, it is very important. */INT shmid ;//... shmid = shmget (my_shm_id, 0, 0); ret = shmctl (shmid, shm_lock, 0); If (ret = 0) printf ("locked! /N "); //////////////////////////////////////// //// // * use the flag to coordinate the shared memory the command gcc-wall test. c-o test. /test create. /test use &. /test use B &. /test read &. /test remove */# include <stdio. h> # include <sys/SHM. h> # include <sys/IPC. h> # include <sys/SEM. h> # include <string. h> # include <stdlib. h> # include <unistd. h> # define my_shm_id 34325 # define my_sem_id 23234 # define max_string 200 typedef struct {int Semid; int counter; char string [max_string + 1];} my_block_t; int main (INT argc, char ** argv) {int shmid, RET, I; my_block_t * block; struct sembuf Sb; char user; // make sure there is a command if (argc> = 2) {// create the shared memory segment and init it // With the semaphore if (! Strncmp (argv [1], "CREATE", 6) {// create the shared memory segment and semaphore printf ("creating the shared memory/N "); shmid = shmget (my_shm_id, sizeof (my_block_t), (ipc_creat | 0666); block = (my_block_t *) shmat (shmid, (const void ); block-> counter = 0; // create the semaphore and init block-> Semid = semget (my_sem_id, 1, (ipc_creat | 0666); sb. sem_num = 0; sb. sem_op = 1; sb. sem_flg = 0; semop (BL Ock-> Semid, & SB, 1); // now detach the segment shmdt (void *) block ); printf ("create the shared memory and semaphore successuflly/N");} else if (! Strncmp (argv [1], "use", 3) {/* use the segment * // must specify also a letter to write to the buffer if (argc <3) exit (-1); User = (char) argv [2] [0]; // grab the segment shmid = shmget (my_shm_id, 0, 0); block = (my_block_t *) shmat (shmid, (const void *) 0, 0 ); /* ######### the key point is to use the flag to access the shared area ########## */for (I = 0; I <100; ++ I) {sleep (1); // when set to 1 S, A/B appears alternately, if the value is 0, A and B appear consecutively // grab the semaphore sb. sem_num = 0; sb. sem_op =-1; sb. sem_flg = 0; If (semop (Block-> Semid, & SB, 1 )! =-1) {// write the letter to the segment buffer // This is our critical section Block-> string [block-> counter ++] = user; sb. sem_num = 0; sb. sem_op = 1; sb. sem_flg = 0; If (semop (Block-> Semid, & SB, 1) =-1) printf ("failed to release the semaphore/N ");} else printf ("failed to acquire the semaphore/N");} // do some clear work ret = shmdt (void *) block);} else if (! Strncmp (argv [1], "read", 4) {// here we will read the buffer in the shared segment shmid = shmget (my_shm_id, 0, 0); If (shmid! =-1) {block = (my_block_t *) shmat (shmid, (const void *) 0, 0); block-> string [block-> counter + 1] = 0; printf ("% s/n", block-> string); printf ("length = % d/N", block-> counter); ret = shmdt (void *) block);} else printf ("unable to read segment/N");} else if (! Strncmp (argv [1], "Remove", 6) {shmid = shmget (my_shm_id, 0, 0); If (shmid> = 0) {block = (my_block_t *) shmat (shmid, (const void *) 0, 0); // remove the semaphore ret = semctl (Block-> Semid, 0, ipc_rmid); If (ret = 0) printf ("successfully remove the semaphore/N"); // remove the shared segment ret = shmctl (shmid, ipc_rmid, 0); If (ret = 0) printf ("successfully remove the segment/N") ;}} else printf ("unkonw command/N") ;}return 0 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.