Mã như sau để bạn tham khảo:
IPC_msgq_rcv.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 128
void die(char *s)
{
perror(s);
exit(1);
}
struct msgbuf
{
long mtype;
char mtext[MAXSIZE];
};
void main()
{
int msqid;
key_t key;
struct msgbuf rcvbuffer;
key = 1234;
if ((msqid = msgget(key, 0666)) < 0)
die("msgget()");
//Receive an answer of message type 1.
if (msgrcv(msqid, &rcvbuffer, MAXSIZE, 1, 0) < 0)
die("msgrcv");
printf("%s\n", rcvbuffer.mtext);
exit(0);
}
IPC_msgq_send.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE 128
void die(char *s)
{
perror(s);
exit(1);
}
struct msgbuf
{
long mtype;
char mtext[MAXSIZE];
};
main()
{
int msqid;
int msgflg = IPC_CREAT | 0666;
key_t key;
struct msgbuf sbuf;
size_t buflen;
key = 1234;
if ((msqid = msgget(key, msgflg)) < 0) //Get the message queue ID for the given key
die("msgget");
//Message Type
sbuf.mtype = 1;
printf("Enter a message to add to message queue : ");
scanf("%[^\n]",sbuf.mtext);
getchar();
buflen = strlen(sbuf.mtext) + 1 ;
if (msgsnd(msqid, &sbuf, buflen, IPC_NOWAIT) < 0)
{
printf ("%d, %ld, %s, %d \n", msqid, sbuf.mtype, sbuf.mtext, (int)buflen);
die("msgsnd");
}
else
printf("Message Sent\n");
exit(0);
}
Compile mỗi nguồn tập tin, để có được một nhà văn-thực thi và đọc-thực thi. Như sau ::
gcc -o MQsender IPC_msgq_send.c
gcc -o MQreceiver IPC_msgq_rcv.c
Thi mỗi người trong số những chương trình, bạn có thể gửi tin nhắn và đọc tin nhắn từ hàng đợi tin nhắn.Ngoài ra, hãy thử để xem trạng thái hàng đợi tin nhắn, bằng cách chạy lệnh (ở tiểu bang khác nhau của hàng đợi):
TVV -q
Đối với hệ thống Linux, bạn có thể biết tất cả các chi tiết của IPC cơ chế và hàng đợi sẵn vv, bằng cách sử dụng:
TVV -a
Reference Blog
Một nhận xét ngắn. Mã của bạn cho khách hàng bị thiếu sau đây bao gồm để làm cho nó biên dịch: '#include #include #include ' –
MKroehnert
Ví dụ rất chi tiết! +++ 1 cảm ơn !! – Viet
Ngọt ngào, tôi yêu thích macro CHECK của bạn. – g33kz0r