unix环境IPC通信之消息队列,并使用多进程的实例

本文介绍了一个使用消息队列进行进程间通信的例子,包括发送和接收消息的进程实现。发送进程通过用户输入来发送不同类型的消息,而接收进程则创建多个子进程来并发地接收这些消息。
/************************************************************************
* *
* 发送消息进程 *
* *
************************************************************************/

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msgt
{
    long msgtype;
    char msgtext[1024];
};
int main()
{
    int msqid;
    int msg_type;
    char str[256];
    struct msgt msgs;
    /* 创建消息队列 */
    msqid = msgget((key_t) 1024, IPC_CREAT);
    while(1)
    {
        printf("please input message type, 0 for quit!\n");
        /* 获取消息类型 */
        scanf("%d",&msg_type);
        /* 如果用户输入的消息类型为0, 退出该循环 */
        if(msg_type == 0)
            break;
        /* 获取消息数据 */
        printf("please input message content !\n");
        scanf("%s", str);
        msgs.msgtype = msg_type;
        strncpy(msgs.msgtext, str, 256);
        /* 发送消息 */
        msgsnd(msqid, &msgs, sizeof(struct msgt), 0);
    }
    /* 删除消息队列 */
    msgctl(msqid, IPC_RMID, 0);
    return 0;
}

/************************************************************************
*									*
*				接收消息进程				*
*									*
************************************************************************/

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
struct msgt
{
    long msgtype;
    char msgtext[1024];
};
int msqid = 0;          // 消息队列的id
void childprocess()
{
    struct msgt msgs;
    while(1)
    {
        // 接收消息队列
        msgrcv(msqid, &msgs, sizeof(struct msgt), 0, 0);
        // 打印消息队列的数据
        printf("msg text : %s\n", msgs.msgtext);
    }
    return;
}
int main()
{
    int i;
    int cpid;
    /* 打开消息队列 */
    msqid = msgget((key_t)1024, IPC_CREAT);
    /* 创建3个子进程 */
    for(i=0; i<3; i++)
    {
        cpid = fork();
        if(cpid < 0)
            printf("creat child process error!\n");
        else if(cpid == 0)
            childprocess();
    }
    return 0;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值