两个无关进程建的消息队列通信

这篇博客探讨了如何让两个不相关的进程通过消息队列实现有效的通信,详细阐述了实现这一通信方式的输入文件、代码实现及运行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

两无关系的进程运用消息队列进行通信
输入文件:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <fcntl.h>
struct msgbuf
    {
        long mtype;         /* 放消息编号,必须 > 0 */
        char mtext[1024];  /* 消息内容(消息正文) */
    };        
int main()
{
    key_t key;
    key = ftok(".", 'a');
    printf("key = [%x]\n",key);
    struct msgbuf msgbuf; 
    int msgid = msgget(key,IPC_CREAT | 0664);
     char buffer[1024];
       while(1)
        {
            printf("send to msg:\n");
            memset(buffer, 0, sizeof(buffer));
            gets(buffer);
            msgbuf.mtype = 1;
            strcpy(msgbuf.mtext,buffer);
            //printf("%s\n",msgbuf.mtext);
            //write(fd,mtext, strlen(mtext));
            //int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
            int ret = msgsnd(msgid,&msgbuf,sizeof(msgbuf.mtext),IPC_NOWAIT);
            if(ret == -1)
            {
                perror("ret error\n");
                exit(1);
            }
        }
   
    pause();
    return 0;
}

输出文件代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <fcntl.h>
struct msgbuf
    {
        long mtype;         /* 放消息编号,必须 > 0 */
        char mtext[1024];  /* 消息内容(消息正文) */
    };        
int main()
{
    key_t key;
    key = ftok(".", 'a');
   int msgid = msgget(key,IPC_CREAT | 0664);
    struct msgbuf msgbuf; 
     int i=1;
       while(1)
       {
        memset(&msgbuf,0,sizeof(msgbuf));
        int ret = msgrcv(msgid,&msgbuf,sizeof(msgbuf.mtext),i,0);
        if(ret == -1)
        {
            perror("error\n");
            return -1;
        }
        printf("recv from msg:[%s]\n",msgbuf.mtext);
       }
    pause();
    return 0;
}

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值