先上官方代码:
send.c:
#include <sys/types.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <stdio.h>
#include <string.h>
struct msgbuf
{
long mtype;
char mtext[1024];
};
void main()
{
int msqid;
int msg_type;
char str[256];
struct msgbuf msgs;
//创建消息队列
msqid = msgget(1024, IPC_CREAT);
//循环
while (1)
{
printf("please enter msg type, 0 for quit:\n");
//获取消息类型
scanf("%d", &msg_type);
//若用户输入的消息类型为0,退出循环
if (msg_type == 0)
break;
//获取消息数据
printf("please enter msg content, 0 for quit:\n");
scanf("%s", str);
msgs.mtype = msg_type;
strcpy(msgs.mtext, str);
//发送消息
msgsnd(msqid, &msgs, sizeof(struct msgbuf), 0);
}
//删除消息队列
msgctl(msqid, IPC_RMID, 0);
return 0;
}
receive.c:
#include <sys/types.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <stdio.h>
#include <stdio.h>
int msqid=0;
struct msgbuf
{
long mtype;
char mtext[1024];
};
void childprocess()
{
struct msgbuf msgs;
int msg_size_flag=0;
while (1)
{
//接收消息队列
msg_size_flag = msgrcv(msqid, &msgs, sizeof(struct msgbuf), 0, 0);
//打印消息队列中的数据
if(msg_size_flag!=-1)
printf("msgs text is %s\n", msgs.mtext);
}
return;
}
void main()
{
int i;
int cpid;
//1、打开消息队列
msqid = msgget(1024, IPC_EXCL);
//2、创建三个子进程
for (i = 0; i < 3; i++)
{
cpid = fork();
if (cpid < 0)
printf("error\n");
else if (cpid == 0)
childprocess();
}
return 1;
}
期间所遇到最严重的问题主要是无法无法接收到消息。
使用命令ipcs -p查看系统正在运行的消息队列:
发现键值为0x400(即1024)的消息队列。尽管之前已经用./send发送过消息,但该队列中并没有消息。
用gdb对receive进行步进调适,发现receive确实读到消息的内容,而ipcs -p也有消息条数的动态变化,因而怀疑是子进程存在某种bug。故此采用一下代码调适:
#include <sys/types.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <stdio.h>
struct msgbuf
{
long mtype;
char mtext[1024];
};
void main()
{
int i;
int cpid;
int msqid=0;
struct msgbuf msgs;
// int msg_size_flag=0;
printf("finish originate ...");
//1、打开消息队列
msqid = msgget(1024, IPC_EXCL);
//2、创建
while (1)
{
printf("waitting messges...");
//接收消息队列
msgrcv(msqid, &msgs, sizeof(struct msgbuf), 0, 0);
//打印消息队列中的数据
printf("msgs text is %s", msgs.mtext);
}
return 1;
}
结果未遂。
故此怀疑是printf的某种机制阻止了输出,百度之后,找到如下博客:
http://velep.com/archives/455.html
据悉linux下的printf有缓存机制,必须遇到\n才会输出,若不用\n可在printf后面加上 fflush(stdout);解决。