一、思维导图

二、消息队列(实现非亲属关系进程间的数据传递)
进程1:
#include <my_head.h>
struct msgbuf
{
long mtype; //必须大于0
char mtext[128]; //数据内容
};
int main(int argc, const char *argv[])
{
//创建秘钥
key_t key=ftok("./",100);
if(key==-1)
{
ERRORLOG("ftok error");
}
printf("ftok success\n");
//创建消息队列
int msgid=msgget(key,IPC_CREAT|0664);
if(msgid==-1)
{
ERRORLOG("msgpid error");
}
//发送消息
while(1)
{
struct msgbuf buf;
printf("请输入数据类型:\n");
scanf("%ld",&buf.mtype);
printf("请输入数据内容:\n");
scanf("%s",buf.mtext);
if(-1==msgsnd(msgid,&buf,sizeof(buf.mtext),0))
{
ERRORLOG("msgsnd error");
}
}
//删除消息队列
if(-1==msgctl(msgid,IPC_RMID,NULL))
{
ERRORLOG("msgctl error");
}
return 0;
}
进程2:
#include <my_head.h>
struct msgbuf
{
long mtype; //必须大于0
char mtext[128]; //数据内容
};
int main(int argc, const char *argv[])
{
//创建秘钥
key_t key=ftok("./",100);
if(key==-1)
{
ERRORLOG("ftok error");
}
printf("ftok success\n");
//创建消息队列
int msgid=msgget(key,IPC_CREAT|0664);
if(msgid==-1)
{
ERRORLOG("msgpid error");
}
//接收消息
struct msgbuf buf;
while(1)
{
long type;
printf("请输入要接收数据类型: ");
scanf("%ld",&type);
if(-1==msgrcv(msgid,&buf,sizeof(buf.mtext),type,0))
{
ERRORLOG("msgsnd error");
}
printf("%ld : %s\n",buf.mtype,buf.mtext);
memset(&buf,0,sizeof(buf));
}
//删除消息队列
if(-1==msgctl(msgid,IPC_RMID,NULL))
{
ERRORLOG("msgctl error");
}
return 0;
}
运行结果

三、牛客刷题

6557

被折叠的 条评论
为什么被折叠?



