分类: C/C++
2010-11-01 21:33:10
/************
创建消息列队
*************/
#include
#include
#include
#include
#include
#include
int main()
{
int qid;
key_t key;
key=(ftok("/home",'a'));
if(key<0)
{
printf("ftok error");
exit(1);
}
qid=msgget(key,IPC_CREAT|0666);
if(qid<0)
{
printf("msgget error");
exit(1);
}
else
printf("Done\n");
return 0;
}
/************
清除消息列队
************/
#include
#include
#include
#include
#include
#include
int main(int argc, char **argv)
{
int qid,status;
if(argc!=2)
{
printf("Too few aruments");
exit(1);
}
qid=atoi(argv[1]);
status=msgctl(qid,IPC_RMD,NULL);
if(status<0)
{
perror("msgctl error");
exit(1);
}
printf("Removed\n");
return 0;
}
/************
消息发送
*************/
#include
#include
#include
#include
#include
#include
#include
#define size 128
struct msgbuf
{
long mtype;
char mtext[size];
};
int main()
{
int qid,ret;
key_t key;
key=(ftok("/home",'a'));
struct msgbuf buf;
if(key<0)
{
printf("ftok error");
exit(1);
}
qid=msgget(key,IPC_CREAT|0666);
if(qid<0)
{
printf("msgget error");
exit(1);
}
while(1)
{
printf("Input the message");
fgets(buf.mtext,size,stdin);
if(strncmp(buf.mtext,"exit",4)==0);
break;
buf.mtype=getpdi();
ret=msgsnd(qid,&buf,size,0);
if(ret<0)
{
printf("msgsnd error");
exit(1);
}
else
printf("Send\n");
}
return 0;
}
/********
消息接收
*********/
#include
#include
#include
#include
#include
#include
#include
#define size 128
struct msgbuf
{
long mtype;
char mtext[size];
};
int main()
{
int qid,ret;
key_t key;
key=(ftok("/home",'a'));
struct msgbuf buf;
if(key<0)
{
printf("ftok error");
exit(1);
}
qid=msgget(key,IPC_CREAT|IPC_EXCL|0666);
if(qid<0)
{
printf("msgget error");
exit(1);
}
while(1)
{
memset(&buf,0,sizeof(buf));
ret=msgrcv(qid,&buf,size,0,0);
if(ret<0)
{
printf("msgsnd error");
exit(1);
}
else
{
printf("Received the message\n");
printf("Type=%d,Length=%d,Text:%s\n",buf.mypte,ret,buf.mtext);
}
}
return 0;
}