• 2023年9月30日


    消息队列实现进程之间通信方式代码

    1. #include
    2. //定义消息构造体
    3. typedef struct
    4. {
    5. long type;
    6. char data[1024];
    7. }msg_ds;
    8. #define SIZE sizeof(msg_ds)-sizeof(long)
    9. int main(int argc, const char *argv[])
    10. {
    11. //创建消息队列
    12. key_t key;
    13. if((key = ftok("/",'k')) == -1)
    14. {
    15. perror("ftok error");
    16. return -1;
    17. }
    18. int msgid;
    19. if((msgid = msgget(key,IPC_CREAT|0774)) == -1)
    20. {
    21. perror("msgget error");
    22. return -1;
    23. }
    24. //发送数据
    25. msg_ds msg = {.type = 100};
    26. while(1)
    27. {
    28. printf("请输入消息:");
    29. fgets(msg.data, sizeof(msg.data),stdin);
    30. msg.data[strlen(msg.data)-1] = '\0';
    31. if(msgsnd(msgid,&msg,SIZE,0)==-1)
    32. {
    33. perror("msgsnd error");
    34. return -1;
    35. }
    36. if(strcmp(msg.data,"quit")==0)
    37. {
    38. break;
    39. }
    40. }
    41. return 0;
    42. }

    1. #include
    2. //消息结构体
    3. typedef struct
    4. {
    5. long type;
    6. char data[1024];
    7. }Msg_ds;
    8. #define SIZE sizeof(Msg_ds)-sizeof(long)
    9. int main(int argc, const char *argv[])
    10. {
    11. //创建key值
    12. key_t key;
    13. if((key = ftok("/", 'k')) == -1)
    14. {
    15. perror("ftok error");
    16. return -1;
    17. }
    18. //创建消息队列
    19. int msgid;
    20. if((msgid = msgget(key, IPC_CREAT|0664)) == -1)
    21. {
    22. perror("msgget error");
    23. return -1;
    24. }
    25. //从消息队列中取数据
    26. Msg_ds msg ;
    27. while(1)
    28. {
    29. //从消息队列中取数据
    30. //第一个0表示取消息的类型,每次都是取第一个
    31. //第二个0表示阻塞方式从消息队列中取数据
    32. if(msgrcv(msgid, &msg, SIZE, 0 ,0) == -1)
    33. {
    34. perror("msgsnd error");
    35. return -1;
    36. }
    37. if(strcmp(msg.data, "quit") == 0)
    38. {
    39. break;
    40. }
    41. printf("rcv: %s\n", msg.data);
    42. }
    43. //删除消息队列
    44. msgctl(msgid, IPC_RMID, NULL);
    45. return 0;
    46. }

  • 相关阅读:
    实现优雅的数据返回 - springboot
    Linux小白零基础必备基础操作【上】
    冲量在线“隐私计算信创一体机”亮相2022世界人工智能大会,获高度关注
    【go】两数求和
    ORM数据库操作
    Matlab:大小写和空格敏感性
    MySQL索引
    奇异矩阵、非奇异矩阵
    openssl调试记录
    宠物医院小程序开发需具备哪些功能?
  • 原文地址:https://blog.csdn.net/2201_75732711/article/details/133434722