• 消息队列实现实时通信


    此实例是一个简单的使用消息队列进行实时聊天的本机通信程序,,发送端每发送一个消息,会立即被接收读取,在没有消息在消息队列中时,将处于阻塞状态。

    终端1运行接收端

    #include <stdio.h>
    #include <string.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/msg.h>
    struct msgbuf
    {
        int type;
        char ptr[0];
    };
    int main(int argc, char *argv[])
    {
        key_t key;
        key=ftok(argv[1],100);
        int msgid;
        msgid=msgget(key,IPC_CREAT|0600);
        pid_t pid;
        pid=fork();
        if(pid==0)
        {
            while(1)
            {
                printf("pls input msg to send:");
                char buf[128];
                fgets(buf,128,stdin);
                struct msgbuf *ptr=malloc(sizeof(struct msgbuf)+strlen(buf)+1);
                ptr->type=2;
                memcpy(ptr->ptr,buf,strlen(buf)+1);
                msgsnd(msgid,ptr,strlen(buf)+1,0);
                free(ptr);
            }
        }
        else
        {
            struct msgbuf
            {
                int type;
                char ptr[1024];
            };
            while(1)
            {
                struct msgbuf mybuf;
                msgrcv(msgid,&mybuf,1024,1,0);
                printf("rcv msg:%s
    ",mybuf.ptr);
            }
    
        }
        return 0;
    }

    终端2运行发送端

    #include <stdio.h>
    #include <string.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/msg.h>
    struct msgbuf
    {
        int type;
        char ptr[0];
    };
    int main(int argc, char *argv[])
    {
        key_t key;
        key=ftok(argv[1],100);
        int msgid;
        msgid=msgget(key,IPC_CREAT|0600);
        pid_t pid;
        pid=fork();
        if(pid==0)
        {
            while(1)
            {
                printf("pls input msg to send:");
                char buf[128];
                fgets(buf,128,stdin);
                struct msgbuf *ptr=malloc(sizeof(struct msgbuf)+strlen(buf)+1);
                ptr->type=1;
                memcpy(ptr->ptr,buf,strlen(buf)+1);
                msgsnd(msgid,ptr,strlen(buf)+1,0);
                free(ptr);
            }
        }
        else
        {
            struct msgbuf
            {
                int type;
                char ptr[1024];
            };
            while(1)
            {
                struct msgbuf mybuf;
                msgrcv(msgid,&mybuf,1024,2,0);
                printf("rcv msg:%s
    ",mybuf.ptr);
            }
    
        }
        return 0;
    }
     
  • 相关阅读:
    正则表达式
    Java 枚举(enum) 详解7种常见的用法
    【20170921】(Unfinished)2017暑假北京学习 day 2
    (Unfinished)2017暑假北京学习 day 2
    Openjudge NOI题库 数论4975 两只鼹鼠
    Openjudge NOI题库 数论185 反正切函数的应用
    Noip1998 提高组3 卢斯加法表
    【自己的小玩具程序】化学方程式配平【测试中】【未完成】
    Code Vs 1010 过河卒
    NOI 练手题 图像旋转翻转变换
  • 原文地址:https://www.cnblogs.com/lakeone/p/3785927.html
Copyright © 2020-2023  润新知