Talk C together (96th back: C language instance -- use shared memory for inter-process communication II)
Hello, everyone. In the previous session, we talked about the example of using the shared memory for inter-process communication. In this session, let's continue with the previous session.Use shared memory for inter-process communication. When you leave the rest of your time, your words will go right. Let's talk C chestnuts together!
In the previous article, we introduced the concept of shared memory and the usage of related functions. In this article, we use specific examples to illustrate how to use shared memory for inter-process communication. The following describes how to use shared memory:
1. defines a struct type, which is used as the shared memory type. 2. use the shmget function to obtain the shared memory. The Random Number 111 is used in the code key. 3. use the shmat function to connect the shared connection to the address space of the process. 4. reads data from the shared memory or writes data to the shared memory. use the shmdt function to separate the shared memory from the address space of the process. 6. use the shmctl function to delete shared memory. The command IPC_RMID is required;
The readers will not write the code in the body, and the detailed code will be put into my resources. You can click here to download and use it.
The following is the running result of the program.For more information, see:
. /S-r // run the program and use the-r parameter to start the data Reading process there is not any data in share memory // there is no data in the shared memory. /s-w // run the program and use the-w parameter to start the data Writing Process write data into share memory. count: 3, data: hello share memory // you are prompted to write data. /s-r // run the program again and use the-r parameter to start the data Reading process the data of share memory. count: 3, data: hello share memory // display the data read from the shared memory
In the program, we use parameters to differentiate different processes and use a tag bit to determine whether data exists in the shared memory. In addition, the synchronization mechanism is required for communication between processes using the shared memory. For example, when we started running the program, there was no write process and no data in the shared memory. At this time, the read process cannot read data from the shared memory.
For more information, see the example of using shared memory for inter-process communication. I want to know what examples will be provided later, and I will try again.