Semaphore, Message Queue, and shared Memory)

Source: Internet
Author: User

System V process Communication Methods: semaphore, Message Queue, and shared Memory)

 

Semaphores

Semaphore is actually an integer whose values are tested and set by multiple processes ). For the test and setup operations that each process is concerned with, these two operations are not interrupted, or they are called "Atomic" operations, that is, once the two operations are started, they are all completed. The result of the test and setup operations is: The current and set values of the semaphore are added, and the sum is positive or negative. Depending on the test and setup results, a process may have to sleep until another process changes the semaphore value.

Semaphores can be used to achieve mutual exclusion between the so-called "critical section". A critical section refers to a code segment where only one process can execute code at a time. To further understand the use of semaphores, the following is an example.

Suppose you have many collaborative processes that are reading or writing records in a data file. You may want to strictly coordinate the access to this file, so you use a semaphore with an initial value of 1 to perform two operations on the semaphore. First, test and subtract 1 from the semaphore value, then test and Add 1 to the semaphore value. When the first process accesses a file, it reduces the semaphore value by 1 and succeeds. The semaphore value is now 0. This process can continue to execute and access the data file. However, if another process also wants to access this file, it also reduces the semaphore value by 1, and the result is that the file cannot be accessed because the semaphore value is-1. This process will be suspended until the first process completes access to the data file. When the first process accesses the data file, it will increase the semaphore value and change it to 1 again. Now, the waiting process is awakened, it will successfully subtract 1 from the semaphore.

See http://www.cnblogs.com/biyeymyhjob/archive/2012/07/21/2602015.html for details

 

Message Queue

A message queue is also called a message queue. A message queue is sustained with the kernel. Only when the kernel restarts or displays the deletion of a message queue, the message queue will delete the data structure struct ipc_ids msg_ids recorded in the system. All message queues in the system can find the access entry in the msg_ids structure.

A message queue is a linked list of messages. Each message queue has a queue header called struct msg_queue. This queue header describes the key value, user ID, and group ID of the message queue, however, it is stored in the kernel, and the struct msqid_ds can return or set Message Queue information, which is located in the user space, similar to the msg_queue structure, a message queue allows one or more processes to write or read messages to it. A message queue is a linked list of messages.

A message is accessed by message type, and the process must specify the message type to read the message. Similarly, when writing a message to a message queue, the message type must also be provided, if the message type used by the read queue is 0, the first message in the queue is read.

The kernel space structure msg_queue describes the corresponding key value message queue, and corresponds to the user space's msqid_ds structure. Therefore, you can operate the msgid_ds structure to operate message queues.

For details, see http://www.cnblogs.com/biyeymyhjob/archive/2012/08/04/2623323.html

 

Shared Memory

Shared memory is the fastest way to communicate between processes running on the same machine, because data does not need to be copied between different processes. A shared memory area is usually created by a process, and other processes read and write this memory area. Shared Memory is often used in conjunction with other communication mechanisms, such as semaphores, to achieve synchronization and mutual exclusion between processes.

Function prototype description see: http://www.cnblogs.com/biyeymyhjob/archive/2012/08/04/2623323.html

Program instance: see http://blog.csdn.net/yangzhongxuan/article/details/7925750

# Include <stdio. h> # include <unistd. h> # include <string. h> # include <sys/ipc. h> # include <sys/shm. h> # include <error. h> # define SIZE 1024int main () {int shmid; char * shmaddr; struct shmid_ds buf; int flag = 0; int pid; // 0 (IPC_PRIVATE ): creates a new shared memory object. IPC_CREAT and IPC Object Access Permissions (such as 0600) are used. | operation is used to determine the shmid = shmget (IPC_PRIVATE, SIZE, IPC_CREAT | 0600) of the semaphore set ); if (shmid <0) {perror ("get shm ipc_id error"); return -1 ;}pid = fork (); if (pid = 0) {shmaddr = (char *) shmat (shmid, NULL, 0 ); // directly specify NULL so that the kernel determines an appropriate address location. if (int) shmaddr =-1) {perror ("shmat addr error "); return-1;} strcpy (shmaddr, "Hi, I am child process! \ N "); // opposite to the shmat function, the shmdt is used to disconnect the address from the additional point of the shared memory and prohibit the process from accessing the shared memory shmdt (shmaddr); return 0 ;} else if (pid> 0) {sleep (3); // controls the shared memory to get the status of the shared memory, copy the shmid_ds structure of the shared memory to the buf. flag = shmctl (shmid, IPC_STAT, & buf); if (flag =-1) {perror ("shmctl shm error "); return-1;} printf ("shm_segsz = % d bytes \ n", buf. shm_segsz); printf ("parent pid = % d, shm_cpid = % d \ n", getpid (), buf. shm_cpid); printf ("chlid pid = % d, shm_lpid = % d \ n", pid, buf. shm_lpid); shmaddr = (char *) shmat (shmid, NULL, 0); if (int) shmaddr =-1) {perror ("shmat addr error "); return-1;} printf ("% s", shmaddr); shmdt (shmaddr); shmctl (shmid, IPC_RMID, NULL); // IPC_RMID: delete this shared memory} else {perror ("fork error"); shmctl (shmid, IPC_RMID, NULL);} return 0 ;}

PS:

An ID value must be specified for the system to establish IPC communication (such as message queue and shared memory. Generally, this id value is obtained through the ftok function.
The ftok prototype is as follows:

key_t ftok( char * fname, int id )

Parameter description:

When fname is used, the document name id you specify is the sub-serial number.

Return Value:

In the general UNIX implementation, the index node number of the document is taken out, and the return value of key_t is obtained by adding the sub-number before it.

For example, if the index node number of a specified document is 65538, it is converted into a hexadecimal value of 0x010002, And the ID value you specified is 38, it is converted into a hexadecimal value of 0x26, then the final key_t return value is 0x26010002.

(The method for querying the document index node number is: ls-I)

 

 

 

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.