📄 21_msg.c
字号:
/* 消息的创建、发送和接收 */
#include<stdio.h>
#include<sys/types.h>
#include<sys/msg.h>
#include<sys/ipc.h>
#define MSGKEY 75 /* 定义关键词MSGKEY */
struct msgform /* 消息结构 */
{
long mtype;
char mtext[1030]; /* 文本长度 */
}msg;
int msgqid,i;
void CLIENT()
{
int i;
msgqid=msgget(MSGKEY,0777);
for (i=10;i>=1;i--)
{
msg.mtype=i;
msg.mtext[1]='h';
msg.mtext[2]='e';
msg.mtext[3]='l';
msg.mtext[4]='l';
msg.mtext[5]='o';
printf("(client)sent\n");
msgsnd(msgqid,&msg,1024,0); /* 发送消息msg入msqid消息队列 */
}
exit(0);
}
void SERVER()
{
msgqid=msgget(MSGKEY,0777|IPC_CREAT);
do
{
msgrcv(msgqid,&msg,1030,0,0); /* 从msqid消息队列接收消息msg */
printf("(server)received\n");
printf("%c%c%c%c%c\n",msg.mtext[1],msg.mtext[2],msg.mtext[3],msg.mtext[4],msg.mtext[5]);
}while(msg.mtype!=1);
msgctl(msgqid,IPC_RMID,0);
exit(0);
}
main()
{
while((i=fork())==-1);
if(!i) SERVER();
while((i=fork())==-1);
if(!i) CLIENT();
wait(0);
wait(0);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -