• 消息队列 两个进程


    参考地址:http://blog.csdn.net/zhsp1029/article/details/2171462

    /*msgserver.c*/

    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/msg.h>
    #include <sys/stat.h>

    #define MSG_FILE "/tmp/msg_logs"
    #define BUFFER 255
    #define PERM S_IRUSR|S_IWUSR
    /* 服务端创建的消息队列最后没有删除,我们要使用ipcrm命令来删除的 */
    /* ipcrm -q <msqid> */

    struct msgtype {
    long mtype;
    char buffer[BUFFER+1];
    };

    int main()
    {
    struct msgtype msg;
    key_t key;
    int msgid;

    if((key=ftok(MSG_FILE,'a'))==-1)
    {
    printf("Creat Key Error:%s/n", strerror(errno));
    exit(1);
    }

    if((msgid=msgget(key, PERM|IPC_CREAT|IPC_EXCL))==-1)
    {
    printf("Creat Message Error:%s/n", strerror(errno));
    exit(1);
    }
    printf("msqid = %d/n", msgid);

    //while(1)
    {
    msgrcv(msgid, &msg, sizeof(struct msgtype), 1, 0);
    printf("Server Receive:%s/n", msg.buffer);
    msg.mtype = 2;
    msgsnd(msgid, &msg, sizeof(struct msgtype), 0);
    if((msgctl(msgid,IPC_RMID,NULL))<0){ //删除消息
    perror("msgctl");
    exit(1);
    }
    }


    exit(0);
    }




    /* msgclient.c */

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

    #define MSG_FILE "/tmp/msg_logs"
    #define BUFFER 255
    #define PERM S_IRUSR|S_IWUSR

    struct msgtype {
    long mtype;
    char buffer[BUFFER+1];
    };

    int main(int argc, char **argv)
    {
    struct msgtype msg;
    key_t key;
    int msgid;

    if(argc != 2)
    {
    fprintf(stderr,"Usage:%s string/n", argv[0]);
    exit(1);
    }

    if((key=ftok(MSG_FILE,'a'))==-1)
    {
    fprintf(stderr,"Creat Key Error:%s/n", strerror(errno));
    exit(1);
    }

    if((msgid=msgget(key, PERM))==-1)
    {
    fprintf(stderr,"Creat Message Error:%s/n", strerror(errno));
    exit(1);
    }

    msg.mtype = 1;
    strncpy(msg.buffer, argv[1], BUFFER);
    msgsnd(msgid, &msg, sizeof(struct msgtype), 0);
    memset(&msg, '/0', sizeof(struct msgtype));
    msgrcv(msgid, &msg, sizeof(struct msgtype), 2, 0);
    fprintf(stderr, "Client receive:%s/n", msg.buffer);
    exit(0);
    }



  • 相关阅读:
    RedisCacheTool参考其中的文件读写功能
    eclipse eayExplorer 查看代码的资源管理器打开方式
    有关写代码效率的问题
    Eclipse
    解决pdm打开只显示表名不显示字段的步骤
    绝对定位元素的水平垂直居中
    Maven依赖之Scope
    无提示关闭弹出窗口
    Maven模块与模块间的依赖
    Maven+Hibernate4注解0配置示例
  • 原文地址:https://www.cnblogs.com/wangkangluo1/p/2287576.html
Copyright © 2020-2023  润新知