您的位置:首页 > 运维架构 > Linux

Linux进程间通信(简单的消息队列通信)

2011-10-21 18:11 302 查看
前几天在计算机操作系统课中学习了Linux下进程通信,今日做了个消息队列通信的简单小程序,权当练习。

程序有服务器和客户端两个进程。先运行服务器,然后客户端。客户端向服务器发送问题,服务器收到后可进行回复。

服务器运行时先判断要创建的消息队列是否存在,若已经存在,则退出。不存在,进入循环。(此为关键。若队列存在仍继续操作,则将二者都收不到消息。(不知为何哈!求高人解释。最早就是再此出耽误了很多时间,还以为是自己程序的毛病呢。))

msgrcv最后个参数设置为0,意思为若当前队列中无消息,则阻塞。等待消息进入队列后接受(即等待客户端启动发送消息) 。然后客户端,服务器无限循环进行问答。若想退出,按ctrl+c。

用到的主要函数:msgget() 创建消息队列 msgrcv()接受消息 msgsnd()发送消息 msgctl()操纵一个消息 fgets()键盘接受字符串,放入message.buffer。详细内容可使用man msgget ....等命令查找。

程序源码如下:

serve.c:

/*Serve process.Write in Ubuntu 11.04*/
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#define Histype 4  //message 的类型。区分服务器和客户端发送的不同消息。接受时,第四个参数设置此类型。下Mytype相同。
#define Mytype 3
#define MY_KEY 20
struct mymessage
{
long mtype;
char buffer[200];
} message;
int msgid;
void server()
{
msgid=msgget(MY_KEY, IPC_CREAT|IPC_EXCL|0666);//IPC_CREAT创建消息,和IPC_EXCL一起使用如果消息已经存在则返回-1;
if(msgid<0)
{
printf("消息队列已经存在!");
exit(0);//消息存在退出.若消息存在仍不退出,则此服务器将陷入死循环。
}
printf("server start:\n");
while(1)
{
msgrcv(msgid,&message,sizeof(struct mymessage),Histype,0);
printf("Question is:\n%s", message.buffer);
printf("Here is the answer :\n");
fgets(message.buffer,sizeof(struct mymessage)-sizeof(long)-1,stdin);//用stdin从键盘接受字符串,存入message.buffer。置于大小的计算,可查指令手册
message.mtype=Mytype;//服务器消息标识
msgsnd(msgid, &message, sizeof(struct mymessage), 0);
}
}
int main()
{
server();
}

client.c:

/*Client process.Write in Ubuntu 11.04*/
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#define Mytype 4
#define Histype 3
#define MY_KEY 20
struct mymessage
{
long mtype;
char buffer[200];
} message;
int msgid;
void client()
{
msgid=msgget(MY_KEY, 0666);//MY_KEY是消息的关键建。唯一标识一个消息。该句返回消息ID
if(msgid>=0)
printf("welcome to numeber %d queue!Input your questions\n",msgid);
else
{
exit(0);//若msgid>=0则说明存在该消息队列。不存在则<0,退出。
}
fgets(message.buffer, sizeof(struct mymessage)-sizeof(long)-1, stdin);
while(1)
{
message.mtype=Mytype;
msgsnd(msgid, &message, sizeof(struct mymessage), 0);
msgrcv(msgid,&message,sizeof(struct mymessage),Histype,0);
printf("The answer is: %sInput your question:\n",message.buffer);
fgets(message.buffer,sizeof(struct mymessage)-sizeof(long)-1,stdin);
}
}
int main()
{
client();
}

运行结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: