interprocess communication IPC--shared memory

Source: Internet
Author: User
Tags int size message queue semaphore strcmp

Each process has a different user address space, the global variables of any one process can not be seen in another process, so the process to exchange data between the kernel, the kernel to open a buffer, process 1 data from the user space to the kernel buffer, process 2 and then read the data from the kernel buffer, This mechanism provided by the kernel is called interprocess communication (ipc,interprocess communication)

As shown: There are seven ways of interprocess communication: The first Category: traditional UNIX communication mechanisms:

# pipe: A pipe is a half-duplex mode of communication in which data can only flow in one direction and can only be used between processes that have affinity. A process's affinity usually refers to a parent-child process relationship.
# famous pipe (named pipe): A well-known pipe is also a half-duplex mode of communication, but it allows communication between unrelated processes.

# signal (sinal): A signal is a more sophisticated means of communication that notifies the receiving process that an event has occurred. Class II: System V IPC:
# semaphore (Semophore): Semaphore is a counter that can be used to control access to shared resources by multiple processes. It is often used as a locking mechanism to prevent a process from accessing the shared resource while other processes are accessing the resource. Therefore, it is primarily used as a means of synchronization between processes and between different threads within the same process.
# message Queue: Message Queuing is a linked list of messages, stored in the kernel and identified by message queue identifiers. Message Queuing overcomes the disadvantages of less signal transmission information, only unformatted byte stream, and limited buffer size.
# Shared Memory: Shared memory is the mapping of memory that can be accessed by other processes, which is created by a process, but can be accessed by multiple processes. Shared memory is the fastest IPC approach and is specifically designed for low-efficiency operation of other interprocess communication modes. It is often used with other communication mechanisms, such as signal two, to achieve synchronization and communication between processes.

Category III: BSD sockets: # Socket: Socket The word is also an inter-process communication mechanism, unlike other communication mechanisms, which can be used for different and inter-process communication. This article describes the shared memory of IPC: Shared memory allows two or more processes to access the same piece of memory, as if the malloc () function returns a pointer to the same physical memory area to a different process. When a process changes the contents of this address, other processes will be aware of the change. The process can read the shared memory directly and does not need to copy the data. Because multiple processes share the same block of memory, there is a need for some kind of synchronization mechanism, both mutexes and semaphores. Steps: The use of shared memory, mainly has the following several Api:ftok (), Shmget (), Shmat (), SHMDT () and Shmctl () ① Create/open Shared memory int shmget (key_t key,int size,int shmflag) For example: Key = Ftok (".", ' m '); Shmid = Shmget (key,1024,0666| Ipc_creat| IPC_EXCL); parameter description: Key: Is the identifier for this shared memory. In the case of inter-process communication between parent and child relationships, this identifier is replaced with Ipc_private. If two processes have no relationship, use Ftok () to figure out an identifier (or define it yourself). Method of generating key: key_t ftok (const char *pathname, int proj_id);1) Pathname must be present in the system and the process can access the2) proj_id is an integer value between 1-255 and a typical value is an ASCII value. such as ' a ', given that the application may be applied on a different host, a key can be defined directly, without ftok obtaining:

#define Ipckey 0x344378

Size: The amount of memory requested Shmflag: The mode of the memory and the permission identifier (0666, etc.).The pattern is preferable to the following values:
Ipc_creat new (returns the ID of the current shared memory if created)
IPC_EXCL is used in conjunction with Ipc_creat and returns an error if created other modes are slightlyThe requested memory is empty, which is all 0
② maps shared memory, which maps the specified shared memory to the process's address space for access to void *shmat (int shmid, char *shmaddr, int shmflag), example: void *p;p=shmat (shmid,null,0); Ming: Shmid: Is the ID of that piece of shared memory. SHMADDR: The starting address of the shared memory map, which is generally not specified as Nullshmflag: The operating mode of the memory for this process. If it is shm_rdonly, it is read-only mode. 0 is the read-write mode return value: When successful, this function returns the starting address of the shared memory. Returns-1 on failure. ③ revoke the shared memory mapping, remove the use of this memory by this process int shmdt (const void* SHMADDR); Example: Shmdt (p); parameter description: Shmaddr: The starting address of the shared memory. Return value: 0 is returned on success. Returns-1 on failure. ④ Delete Shared Memory object int shmctl (int shmid, int cmd, struct shmid_ds *buf); Example: Shmctl (Shmid, Ipc_rmid, NULL);(Delete shared memory)
Parameter description: Shmid: The ID of the shared memory.
CMD: Control command, the following values are desirable:
Ipc_stat get the state of shared memory
Ipc_set changing the state of shared memory
Ipc_rmid Deleting shared memory
BUF: A struct-body pointer. Used to save/set properties. When Ipc_stat, the acquired state is placed in the structure. If you want to change the state of shared memory, specify it with this struct.
Return value: 0 is returned on success. Returns-1 on failure.no code, no truth .Function Description: Two processes through shared memory one writes one reads and prints the data
  1. /*name:writer.c
  2. *function: write-side process writes data to shared memory
  3. * */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <unistd.h>
  7. #include <errno.h>
  8. #include <signal.h>
  9. #include <string.h>
  10. #include <sys/types.h>
  11. #include <sys/ipc.h>
  12. #include <sys/shm.h>
  13. #define N 64
  14. typedef struct
  15. {
  16. pid_t pid;
  17. Char Buf[n];
  18. } SHM;
  19. void handler (int signo)
  20. {
  21. printf ("Get signal\n");
  22. Return
  23. }
  24. int main ()
  25. {
  26. key_t key;
  27. int shmid;
  28. SHM *p;
  29. pid_t pid;
  30. if (key = Ftok (".", ' m ')) < 0)
  31. {
  32. Perror ("fail to Ftok");
  33. Exit (-1);
  34. }
  35. Signal (SIGUSR1, handler);//Register a signal processing function
  36. if (Shmid = Shmget (key, sizeof (SHM), 0666| Ipc_creat| IPC_EXCL)) < 0)
  37. {
  38. if (eexist = = errno)//exist directly open
  39. {
  40. Shmid = Shmget (key, sizeof (SHM), 0666);
  41. p = (SHM *) Shmat (shmid, NULL, 0);
  42. PID = p->pid;
  43. P->pid = Getpid ();
  44. Kill (PID, SIGUSR1);
  45. }
  46. else//Error
  47. {
  48. Perror ("fail to Shmget");
  49. Exit (-1);
  50. }
  51. }
  52. else//success
  53. {
  54. p = (SHM *) Shmat (shmid, NULL, 0);
  55. P->pid = Getpid ();//write your own PID to shared memory
  56. Pause ();
  57. PID = p->pid;//to get the PID of the read-end process
  58. }
  59. while (1)
  60. {
  61. printf ("Write to SHM:");
  62. Fgets (P->buf, N, stdin);//Receive Input
  63. Kill (PID, SIGUSR1);//Send SIGUSR1 signal to the reading process
  64. if (strcmp (P->buf, "quit\n") = = 0) break;
  65. Pause ();//block, wait for signal
  66. }
  67. SHMDT (P);
  68. Shmctl (Shmid, Ipc_rmid, NULL);//delete shared memory
  69. return 0;
  70. }
  1. /*name:reader.c
  2. *function: read-side process reads data from shared memory
  3. * */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <unistd.h>
  7. #include <errno.h>
  8. #include <signal.h>
  9. #include <string.h>
  10. #include <sys/types.h>
  11. #include <sys/ipc.h>
  12. #include <sys/shm.h>
  13. #define N 64
  14. typedef struct
  15. {
  16. pid_t pid;
  17. Char Buf[n];
  18. } SHM;
  19. void handler (int signo)
  20. {
  21. printf ("Get signal\n");
  22. Return
  23. }
  24. int main ()
  25. {
  26. key_t key;
  27. int shmid;
  28. SHM *p;
  29. pid_t pid;
  30. if (key = Ftok (".", ' m ')) < 0)
  31. {
  32. Perror ("fail to Ftok");
  33. Exit (-1);
  34. }
  35. Signal (SIGUSR1, handler);//Register a signal processing function
  36. if (Shmid = Shmget (key, sizeof (SHM), 0666| Ipc_creat| IPC_EXCL)) < 0)
  37. {
  38. if (eexist = = errno)//exist directly open
  39. {
  40. Shmid = Shmget (key, sizeof (SHM), 0666);
  41. p = (SHM *) Shmat (shmid, NULL, 0);
  42. PID = p->pid;
  43. P->pid = Getpid ();//write your own PID to shared memory
  44. Kill (PID, SIGUSR1);
  45. }
  46. else//Error
  47. {
  48. Perror ("fail to Shmget");
  49. Exit (-1);
  50. }
  51. }
  52. else//success
  53. {
  54. p = (SHM *) Shmat (shmid, NULL, 0);
  55. P->pid = Getpid ();
  56. Pause ();
  57. PID = p->pid;//to get the PID of the write End process
  58. }
  59. while (1)
  60. {
  61. Pause ();//block, wait for signal
  62. if (strcmp (P->buf, "quit\n") = = 0) exit (0);//enter "Quit End"
  63. printf ("read from SHM:%s", p->buf);
  64. Kill (PID, SIGUSR1);//Send SIGUSR1 signal to the writing process
  65. }
  66. return 0;
  67. }

interprocess communication IPC--shared memory

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.