消息队列不同进程之间通信

来源:互联网 发布:天刀最帅捏脸数据 编辑:程序博客网 时间:2024/06/17 22:28

/*msglucy.c*/

#include<sys/ipc.h>
#include<sys/msg.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<stdio.h>
#include<fcntl.h>
#include<signal.h>
#include<stdlib.h>
#include<string.h>

#define PROJID 0XFF
#define LUCY 1
#define PETER 2

int mqid;
void terminate_handler(int );

void terminate_handler(int signo)
{
msgctl(mqid,IPC_RMID,NULL);
exit(0);
}

int main()
{
char filenm[]="msg";
key_t mqkey;
struct msgbuf
{
    long mtype;
    char mtext[256];
}msg;
int ret;

mqkey = ftok(filenm,PROJID);
if(mqkey==-1)
{
    perror("ftok error:");
    exit(-1);
}
/*IPC_CREAT   如果共享内存不存在,则创建一个共享内存,否则打开操作。 */
/*IPC_EXCL     只有在共享内存不存在的时候,新的共享内存才建立,否则就产生错误*/
/*0666  对应高级环境编程p417,表示读写权限*/
mqid = msgget(mqkey,IPC_CREAT|IPC_EXCL|0666);
if(mqid==-1)
{
    perror("msgget error:");
    exit(-1);
}

signal(SIGINT,terminate_handler);/*SIGINT  终端中断符*/
signal(SIGTERM,terminate_handler);/*SIGTERM  终止*/

while(1)
{
    printf("Lucy:");
    fgets(msg.mtext,256,stdin); /*get the msg from the screen*/
    if(strncmp("quit",msg.mtext,4)==0)
    {
    msgctl(mqid,IPC_RMID,NULL); /*delete all the quene and data*/
    exit(0);
    }
    msg.mtext[strlen(msg.mtext)-1] = '\0';
    msg.mtype = LUCY;
    msgsnd(mqid,&msg,strlen(msg.mtext)+1,0);
    msgrcv(mqid,&msg,256,PETER,0);/*return the first msg of quene*/
    printf("Peter:%s\n",msg.mtext);
}
}

/*msgpeter.c*/

#include<sys/ipc.h>
#include<sys/msg.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<stdio.h>
#include<fcntl.h>
#include<signal.h>
#include<stdlib.h>
#include<string.h>

#define PROJID 0XFF
#define LUCY 1
#define PETER 2

int main()
{
char filenm[]="msg";
int mqid;
key_t mqkey;
struct msgbuf
{
    long mtype;
    char mtext[256];
}msg;
int ret;

mqkey = ftok(filenm,PROJID);
if(mqkey==-1)
{
    perror("ftok error:");
    exit(-1);
}

mqid = msgget(mqkey,0);
if(mqid==-1)
{
    perror("msgget error:");
    exit(-1);
}

while(1)
{
    msgrcv(mqid,&msg,256,LUCY,0);
    printf("LUCY:%s\n",msg.mtext);
    printf("Peter:");
    fgets(msg.mtext,256,stdin);
    if(strncmp("quit",msg.mtext,4)==0)
    {
    msgctl(mqid,IPC_RMID,NULL);
    exit(0);
    }
    msg.mtext[strlen(msg.mtext)-1] = '\0';
    msg.mtype = PETER;
    msgsnd(mqid,&msg,strlen(msg.mtext)+1,0);
}
}

需要手工创建一个名字为msg的空文件,然后先运行lucy再运行peter,可以相互发送信息