Reference: http://www.linuxidc.com/Linux/2011-08/39738.htm
# Include <sys/types. h>
# Include <sys/IPC. h>
# Include <sys/msg. h>
# Include <stdio. h>
# Include <stdlib. h>
# Include <unistd. h>
# Include < String . H>
# Define Bufsz512
Struct Message { // Message structure
Long Msg_type;
Char Msg_text [bufsz];
};
Int Main ()
{
Int Qid;
Key_t key;
Int Len;
Struct Message MSG;
If (Key = ftok ( " . " , ' A ' ) =- 1 ) // Ftok gets a key
{
Perror ( " Ftok " );
Exit ( 1 );
}
If (Qid = msgget (Key, ipc_creat | 0666 ) =-1 ){ // Create a Message Queue
Perror ( " Msgget " );
Exit ( 1 );
}
Printf ( " Opened queue % d \ n " , Qid );
Puts ( " Please enter the message to queue: " );
If (Fgets (msg. msg_text, bufsz, stdin) = NULL) // Get input from standard input
{
Puts ( " No message " );
Exit ( 1 );
}
MSG. msg_type = getpid ();
Len = strlen (msg. msg_text );
If (Msgsnd (qid, & MSG, Len, 0 ) < 0 ){ // Send message
Perror ( " Message posted " );
Exit ( 1 );
}
If (Msgrcv (qid, & MSG, bufsz, 0 ,0 ) < 0 ){ // Receive messages
Perror ( " Msgrcv " );
Exit ( 1 );
}
Printf ( " Message is: % s \ n " , (& MSG)-> msg_text );
If (Msgctl (qid, ipc_rmid, null) < 0 ){ // Delete message
Perror ( " Msgctl " );
Exit ( 1 );
}
Exit ( 0 );
}
End