Message Queue Process Communication

Source: Internet
Author: User

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

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.