This article provides a simple example to introduce the message queue in Linux. There are two sections of code to simulate blocking chat. Let's look at the code below!
Msgserver. c
# Include <stdio. h>
# Include <fcntl. h>
# Include <stdlib. h>
# Include <sys/types. h>
# Include <sys/IPC. h>
# Include <sys/msg. h>
# Include <sys/STAT. h>
# Define buf_size 256
# Define proj_id 32
# Define path_name "/tmp"
# Define server_msg 1
# Define client_msg 2
Int main (void ){
/* Custom message buffer */
Struct mymsgbuf {
Long msgtype;
Char ctrlstring [buf_size];
} Msgbuffer;
Int qid;
Int msglen;
Key_t msgkey;
/* Obtain the key value */
If (msgkey = ftok (path_name, proj_id) =-1)
{
Perror ("ftok error! \ N ");
Exit (1 );
}
/* Get the message queue identifier */
If (qid = msgget (msgkey, ipc_creat | 0660) =-1)
{
Perror ("msgget error! \ N ");
Exit (1 );
}
While (1)
{
Printf ("server :");
Fgets (msgbuffer. ctrlstring, buf_size, stdin );
If (strncmp ("exit", msgbuffer. ctrlstring, 4) = 0)
{
Msgctl (qid, ipc_rmid, null );
Break;
}
Msgbuffer. ctrlstring [strlen (msgbuffer. ctrlstring)-1] = '\ 0 ';
Msgbuffer. msgtype = server_msg;
If (msgsnd (qid, & msgbuffer, strlen (msgbuffer. ctrlstring) + 1, 0) =-1)
{
Perror ("server msgsnd error! \ N ");
Exit (1 );
}
If (msgrcv (qid, & msgbuffer, buf_size, client_msg, 0) =-1)
{
Perror ("server msgrcv error! \ N ");
Exit (1 );
}
Printf ("client: % s \ n", msgbuffer. ctrlstring );
}
Exit (0 );
}
Msgclient. c
# Include <stdio. h>
# Include <fcntl. h>
# Include <stdlib. h>
# Include <string. h>
# Include <sys/types. h>
# Include <sys/IPC. h>
# Include <sys/msg. h>
# Include <sys/STAT. h>
# Define buf_size 256
# Define proj_id 32
# Define path_name "/tmp"
# Define server_msg 1
# Define client_msg 2
Int main (void)
{
/* Custom message buffer */
Struct mymsgbuf {
Long msgtype;
Char ctrlstring [buf_size];
} Msgbuffer;
Int qid;/* Message Queue identifier */
Int msglen;
Key_t msgkey;
/* Obtain the key value */
If (msgkey = ftok (path_name, proj_id) =-1)
{
Perror ("ftok error! \ N ");
Exit (1 );
}
If (qid = msgget (msgkey, ipc_creat | 0660) =-1)
{
Perror ("msgget error! \ N ");
Exit (1 );
}
While (1)
{
If (msgrcv (qid, & msgbuffer, buf_size, server_msg, 0) =-1)
/* If queue is empty, block here */
{
Perror ("server msgrcv error! \ N ");
Exit (1 );
}
Printf ("server: % s \ n", msgbuffer. ctrlstring );
Printf ("client :");
Fgets (msgbuffer. ctrlstring, buf_size, stdin );
If (strncmp ("exit", msgbuffer. ctrlstring, 4) = 0)
{
Break;
}
Msgbuffer. ctrlstring [strlen (msgbuffer. ctrlstring)-1] = '\ 0 ';
Msgbuffer. msgtype = client_msg;
If (msgsnd (qid, & msgbuffer, strlen (msgbuffer. ctrlstring) + 1, 0) =-1)
{
Perror ("client msgsnd error! \ N ");
Exit (1 );
}
}
Exit (0 );
}