Inter-process communication (4)-shared memory, Process Communication shared memory

Source: Internet
Author: User

Inter-process communication (4)-shared memory, Process Communication shared memory

I will use several blogs to summarize several methods of communication between processes in Linux. I will write the summary at the beginning in each blog of this series.

Communication between processes

  • MPs queue
  • Message Queue
  • Signal
  • Semaphores
  • Shared storage Zone
  • Socket)

Inter-process communication (III)-semaphore Portal: http://www.cnblogs.com/lenomirei/p/5649792.html

Inter-process communication (II)-Message Queue Portal: http://www.cnblogs.com/lenomirei/p/5642575.html

Inter-process communication (I)-pipe Portal: http://www.cnblogs.com/lenomirei/p/5636339.html

This article mainly records the operations related to the shared storage area, that is, the shared storage area. In fact, the shared memory is used, and the process can communicate with each other in the storage area.

Why do I use a shared storage area for communication? Because it is fast!The pipeline is a file, the operation is slow, and the message queue creation operation consumes a lot of time. The shared memory requires two processes to be created to directly operate on this memory, which is visible to each other.

Why write programs in a shared storage area? The interface is simple!Operations are much easier than message queues.

  • Create a shared storage Zone

Although it feels very simple, you still needOtherwise, each process maps its own address space to different physical addresses. Even if the virtual addresses are the same, they are independent and invisible to each other, after the shared storage area is declared, it can be mapped to this public area (this is useful, isn't it ).

  • Function prototype: int shmget (key_t key, size_t size, int shmflg );
  • Header file: # include <sys/ipc. h> # include <sys/shm. h>
  • Parameter Parsing
    • The key parameter is obtained through the return value of the ftok function, or the input IPC_PRIVATE is automatically allocated by the operating system.
    • Size indicates how much shared storage space you want to open up,PS: The allocated space will eventually become the physical space allocated by allocating the entire page. in Linux, the size of the next page is 4KB = 4096B, and a page is allocated if it is smaller than 4096B, if size is set to 4097, two pages are allocated.
    • Shmflg has IPC_CREAT and IPC_EXCL

You can call this function to create a shared storage area. You can use ipcs-m to view the status of the current shared storage area.

The first key value is the input key, and the shmid identifies the unique shared memory segment. The owner permission byte does not have much to say. This nattch refers to the number of processes currently connected to the shared storage zone.

Nattch: it is not enough to create a shared storage zone. You need to link it with the process to map an address segment of the process's address space to the shared memory segment.

  • Shared storage zone connection

Which of the following functions can be used to connect to the shared storage area,Note that both processes need to be linked. The process that creates a shared storage area will not be automatically connected. You also need to call the linked function.

  • Function prototype: void * shmat (int shmid, const void * shmaddr, int shmflg );
  • Header file: # include <sys/types. h> # include <sys. shm. h>
  • Parameter Parsing
    • Shmid indicates the ID of the shared storage area
    • The second parameter indicates the start address of the shared storage area,If you are not familiar with the memory, you are advised to submit it to the operating system., Set to 0
    • Shmflg can set the read and write permissions of the current process, such as SEM_RDONLY. The default value 0 indicates read and write permissions, and the test program I gave 0

Every time a process calls this function, it will increase the value of nattch by 1. The returned value is because it is a null pointer and often needs to be forcibly converted.

  • Disconnection of the shared storage area

It is a good habit to disconnect links after they are used, and it is good for destroying shared buckets.

  • Function prototype: int shmdt (const void * shmaddr );
  • Header file: # include <sys/types. h> # include <sys. shm. h>
  • Parameter resolution Delete shared storage Zone
    • It is the starting address of the shared storage area to be deleted. Because it is a null pointer, there is no need to convert it and it can be deleted directly.

 

 

  • Delete a shared storage Zone

Finally, we need to use the shmctl function to delete the shared storage zone.

  • Function prototype: int shmctl (int shmid, int cmd, struct shmid_ds * buf );
  • Header file: # include <sys/ipc. h> # include <sys/shm. h>
  • Parameter Parsing
    • Shmid indicates the ID of the shared storage area
    • Cmd provides IPC_RMID to indicate deletion.
    • Because the second parameter is set to IPC_RMID to indicate deletion, the third parameter is useless, and the third parameter is directly NULL (0)

 

Now, the basic operations have been completed,Show me the code

My program is divided into three files: comm. h (Public header file) comm. c (encapsulate basic functions) server. c (Simple server)

Function mainly implements simple string sharing? Writing by the parent process and printing by the child process

The result graph does not show any ghosts.

Comm. h

 1 #include <stdio.h> 2 #include <sys/types.h> 3 #include <string.h> 4 #include <sys/ipc.h> 5 #include <unistd.h> 6 #include <sys/shm.h> 7 #include <errno.h> 8 #include <stdlib.h> 9 10 11 #define _PATH_NAME_ "/tmp"12 #define _PROJ_ID_ 0x666613 14 15 16 static int comm_create_ssm(int flags,size_t size);17 int create_shm(size_t size);18 int get_shm();19 char *shm_at(int shm_id);20 void destory_shm(int shm_id);21 int shm_dt(char *addr);

 

Comm. c

 1 #include "comm.h" 2  3  4 static int comm_create_shm(int flags,size_t size) 5 { 6   key_t _key=ftok(_PATH_NAME_,_PROJ_ID_); 7   if(_key<0) 8   { 9     printf("%d:%s",errno,strerror(errno));10   }11   int shm_id;12   if((shm_id=shmget(_key,size,flags))<0)13   {14     printf("shmget error,%d:%s",errno,strerror(errno));15   }16   return shm_id;17 }18 19 20 int create_shm(size_t size)21 {22   int flags=IPC_CREAT |IPC_EXCL;23   return comm_create_shm(flags,size);24 }25 26 int get_shm()27 {28   int flags=IPC_CREAT;29   return comm_create_shm(flags,0);30 }31 32 char *shm_at(int shm_id)33 {34   return (char *)shmat(shm_id,NULL,0);35 }36 int shm_dt(char *addr)37 {38   return shmdt(addr);39 }40 41 void destory_shm(int shm_id)42 {43   shmctl(shm_id,IPC_RMID,0);44 }

 

Server. c

 1 #include "comm.h" 2  3  4  5 int main() 6 { 7   int pid=fork(); 8   if(pid>0) 9   {10     //father11     int shm_id=create_shm(4096);12     char *buf=shm_at(shm_id);13     int i=0;14     while(i<4096)15     {16       sleep(1);17       buf[i]='A';18       i++;19       buf[i]='\0';20     }21   }22   else23   {24     //child25     int shm_id=get_shm();26     char *buf=shm_at(shm_id);27     while(1)28     {29       sleep(1);30       printf("%s\n",buf);31     }32   }33   return 0;34 }

 

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.