What I learned about linux and the operating system

Source: Internet
Author: User
What I learned about linux and the operating system-general Linux technology-Linux programming and kernel information. The following is a detailed description. Process Communication (message sending and receiving experiment)
1. What is a message?
A message is a formatted unit of variable length information. The message mechanism allows a process to send a message to any other process. When a process receives multiple messages, it can arrange them into a message queue. A message uses two important data structures: one is the message header, which records information related to the message, such as the number of bytes of the message data; the other two are Message Queue headers, each table entry is the message header of a message queue, which records information about the message queue.
1. Data Structure of the Message Mechanism
(1) Message Header
Records message-related information, such as the type, size, pointer to the message data area, and link pointer to the message queue.
(2) Message Queue header table
Each item serves as the message header of a message queue, records the relevant information of the message queue, such as the pointer to the first message and the last message in the message queue, the number of messages in the queue, the total number of bytes of message data in the queue maximum number of bytes allowed for message data, there are also process identifiers and times of the last send operation, process identifiers and times of the last receive operation, and so on.
2. Message Queue Descriptor
In LINUX, each message queue has a name called the key, which is specified by the user. The message queue has a message queue descriptor, which serves the same purpose as the user file descriptor, it is also used to facilitate access to message queues by users and systems.

Ii. involved system calls
1. msgget ()
Create a message to obtain the message descriptor. The core searches for the message queue header table to determine whether a Message Queue with the specified name exists. If no message queue is available, the core allocates a new message queue header, initializes it, and returns a Message Queue descriptor to the user. Otherwise, it only returns the Message Queue permission check.
System Call format:
Msgqid = msgget (key, flag)
The function uses the following header file:
# I nclude
# I nclude
# I nclude
Parameter Definition
Int msgget (key, flag)
Key_t key;
Int flag;
Where:
The key is the name of the Message Queue specified by the user, and the flag is the identifier and access method set by the user. For example, IPC_CREAT | 0400 indicates whether the queue has been created. If none, it is created. If yes, it is enabled;
IPC_EXCL | 0400 whether to create a queue is mutually exclusive.
Msgqid is the descriptor returned by the system call. If the call fails,-1 is returned.
2. msgsnd ()
Send a message. Sends a message to the specified message queue and links the message to the end of the message queue.
System Call format:
Msgsnd (msgqid, msgp, size, flag)
The function uses the following header file:
# I nclude
# I nclude
# I nclude
Parameter definition:
Int msgsnd (msgqid, msgp, size, flag)
I int msgqid, size, flag;
Struct msgbuf * msgp;
Msgqid is the descriptor of the returned message queue, and msgp is a struct pointer pointing to the user message buffer. The buffer includes the Message Type and message body, that is
{
Long mtype;/* Message Type */
Char mtext [];/* message text */
}
Size indicates the length of the character array in the data structure directed by msgp; that is, the length of the message. The maximum value of this array is determined by the MSG-MAX () system callable parameters. Flag specifies the action that should be performed when the core uses up the internal buffer space: whether the process is waiting or returns immediately. If the IPC_NOWAIT bit is not set in the flag, the msgsnd process is called to sleep when the number of bytes in the message queue exceeds the maximum value or the number of messages in the system range exceeds the maximum value. If IPC_NOWAIT is set, msgsnd returns immediately.
For msgsnd (), the core must do the following:
(1) Check the Message Queue descriptor, permission, and message length. If it is valid, the execution will continue; otherwise, the execution will be returned;
(2) The core is the message data zone for message distribution. Copy the message body in the user message buffer to the message data zone;
(3) Allocate the message header and link it to the end of the message queue. In the message header, you must enter the message type, Message Size, pointer to the message data area, and other data;
(4) modify the data in the message queue header, such as the number of messages in the queue and the total number of bytes. Finally, wake up the process waiting for the message.
3. msgrcv ()
Accept a message. Receives messages of the specified type from the specified message queue.
System Call format:
Msgrcv (msgqid, msgp, size, type, flag)
The header file used by this function is as follows:
# I nclude
# I nclude
# I nclude
Parameter definition:
Int msgrcv (msgqid, msgp, size, type, flag)
Int msgqid, size, flag;
Struct msgbuf * msgp;
Long type;
Among them, msgqid, msgp, size, and flag are similar to the corresponding parameters in msgsnd. type is the type of message to be read. flag specifies the operations that the core should do if the queue has no message. If the IPC_NOWAIT flag is set at this time, return immediately. If MS_NOERROR is set in the flag and the received message is greater than the size, the core truncates the received message.
For msgrcv system calls, the core must complete the following work:
(1) Check Message Queue descriptors and permissions. If it is valid, execute the following command; otherwise, return;
(2) Processing Based on Different types is divided into three situations:
Type = 0. receives the first message from the queue and returns it to the caller;
Type is a positive integer that receives the first message of type;
Type is a negative integer that receives the first message of the lowest type that is less than or equal to the absolute value of type.
(3) When the returned Message Size is equal to or less than the user's request, the core copies the message body to the user area and deletes the message from the message queue, then wake up the sleeping sending process. However, if the message length is larger than the required size, an error is returned.
4. msgctl ()
Message Queue control. Read and modify the status information of a message queue, such as querying the Message Queue descriptor, modifying its permission, and deleting the queue.
System Call format:
Msgctl (msgqid, cmd, buf );
The header file used by this function is as follows:
# I nclude
# I nclude
# I nclude
Parameter definition:
Int msgctl (msgqid, cmd, buf );
Int msgqid, cmd;
Struct msgqid_ds * buf;
If the function call is successful, 0 is returned. If the call is unsuccessful,-1 is returned. Buf is the user's buffer address for users to store control parameters and query results. cmd is a required command. Commands can be divided into three types:
(1) IPC_STAT. Query the message queue. Such as querying the number of messages in the queue, the maximum number of bytes in the queue, the process identifier of the last message to be sent, and the sending time;
(2) IPC_SET. Set and change the command about Message Queue attributes by the value in the structure pointed to by buf. For example, changing the user ID of a message queue and the permission of a message queue;
(3) IPC_RMID. Removes the identifier of a message queue.
The msgqid_ds structure is defined as follows:
Struct msgqid_ds
{Struct ipc_perm msg_perm;/* permission structure */
Short pad1 [7];/* used by the system */
Ushort msg_qnum;/* Number of messages in the queue */
Ushort msg_qbytes;/* Maximum number of bytes in the queue */
Ushort msg_lspid;/* PID of the last message sent */
Ushort msg_lrpid;/* PID of the last message received */
Time_t msg_stime;/* time when the last message is sent */
Time_t msg_rtime;/* time when the last message is received */
Time_t msg_ctime;/* last modification time */
};
Struct ipc_perm
{Ushort uid;/* Current user */
Ushort gid;/* Current Process Group */
Ushort cuid;/* create user */
Ushort cgid;/* Create A Process Group */
Ushort mode;/* access permission */
{Short pid1; long pad2;}/* used by the system */
}

Iii. Reference procedure
1. client. c
# I nclude
# I nclude
# I nclude
# Define MSGKEY 75
Struct msgform
{Long mtype;
Char mtext [1000];
} Msg;
Int msgqid;

Void client ()
{
Int I;
Msgqid = msgget (MSGKEY, 0777);/* Open 75 # Message Queue */
For (I = 10; I> = 1; I --)
{
Msg. mtype = I;
Printf ("(client) sent \ n ");
Msgsnd (msgqid, & msg, 0);/* send a message */
}
Exit (0 );
}

Main ()
{
Client ();
}

2. server. c
# I nclude
# I nclude
# I nclude
# Define MSGKEY 75
Struct msgform
{Long mtype;
Char mtext [1000];
} Msg;
Int msgqid;

Void server ()
{
Msgqid = msgget (MSGKEY, 0777 | IPC_CREAT);/* Create 75 # Message Queue */
Do
{
Msgrcv (msgqid, & msg, 0, 0);/* receive messages */
Printf ("(server) received \ n ");
} While (msg. mtype! = 1 );
Msgctl (msgqid, IPC_RMID, 0);/* Delete the message queue and return the resource */
Exit (0 );
}

Main ()
{
Server ();
}

Iv. program description
1. For ease of operation and observation, two programs client. c and server. c are compiled for sending and receiving messages respectively.
2. The server creates a Message Queue with a Key of 75 and waits for messages sent from other processes. When a message of type 1 is encountered, it is used as the end signal to cancel the queue and exit the server. After receiving a message, the server displays "(server) received ed ."
3. The client uses a Message Queue with a key of 75 to send messages ranging from 10 to 1, and then exits. The last message is the end signal required by the server. After each message is sent, the client displays the "(client) sent ".
4. Note: The two programs are edited and compiled into the client and server respectively. Run:
./Server &
Ipcs-q
./Client.

V. Running result
Ideally, each time the client sends a message, the server receives the message and the client sends the Next message. That is to say, the words "(client) sent" and "(server) received" should alternate on the screen. Most of the actual results are: the client sends two messages first, and then the server receives one message. After that, the client and server send and receive messages alternately. The last server receives two messages at a time. The client and server send and receive 10 messages respectively, which is consistent with the expectation.
Related Article

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.