linux系統程式設計——訊息佇列對資料進行收發
阿新 • • 發佈:2021-02-16
linux系統程式設計——訊息佇列對資料進行收發
0777可讀可寫可執行
傳送資料
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
//1.int msgget(key_t key, int msgflg);
//2. int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
// ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,
// int msgflg);
struct msgbuf {
long mtype; //型別
char mtext[128]; //內容
};
int main()
{
//1.獲取並建立佇列
struct msgbuf sendbuf={888,"this is from que"};
struct msgbuf readbuf;
int msgId=msgget (0x1235,IPC_CREAT|0777);
if(msgId==-1)
{
printf("get msg failed\n");
}
msgsnd(msgId,&sendbuf,strlen(sendbuf.mtext),0);
printf("send over\n");
msgrcv(msgId,&readbuf,sizeof(readbuf.mtext),988,0);
printf("return from get:%s\n" ,readbuf.mtext);
return 0;
}
接受資料
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
//1.int msgget(key_t key, int msgflg);
//2. int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
// ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,
// int msgflg);
struct msgbuf {
long mtype; //型別
char mtext[128]; //內容
};
int main()
{
//1.獲取並建立佇列
struct msgbuf readbuf;
int msgId=msgget(0x1235,IPC_CREAT|0777);
if(msgId==-1)
{
printf("get msg failed\n");
}
//2.接受
msgrcv(msgId,&readbuf,sizeof(readbuf.mtext),888,0);
printf("read from que:%s\n",readbuf.mtext);
struct msgbuf sendbuf={988,"thank your for reach"};
msgsnd(msgId,&sendbuf,strlen(sendbuf.mtext),0);
return 0;
}
傳送:
接受:
——@上官可程式設計