• 5月13号作业


    使用消息队列实现的2个终端之间的互相聊天 并使用信号控制消息队列的读取方式: 当键盘按ctrl+c的时候,切换消息读取方式,一般情况为读取指定编号的消息,按ctrl+c之后,指定的编号不读取,读取其他所有编号的消息

    1. #include
    2. #include
    3. #include
    4. #include
    5. #include
    6. #include
    7. #include
    8. #include
    9. #include
    10. #include
    11. #include
    12. #include
    13. #include
    14. #include
    15. #include
    16. #include
    17. #include
    18. #include
    19. #include
    20. #include
    21. int brr=0;
    22. struct msgbuf
    23. {
    24. long mtype;
    25. char mtext[128];
    26. };
    27. void *run(void *arg)
    28. {
    29. int* mytype=(int*)arg;
    30. key_t key=ftok("./ipc",1);
    31. if(key==-1)
    32. {
    33. perror("ftok");
    34. return NULL;
    35. }
    36. int id=msgget(key,IPC_CREAT|0666);
    37. if(id==-1)
    38. {
    39. perror("msgget");
    40. return NULL;
    41. }
    42. struct msgbuf msg;
    43. int size=0;
    44. while(1)
    45. {
    46. if(brr==0)
    47. {
    48. memset(&msg,0,sizeof(msg));
    49. msgrcv(id,&msg,128,*mytype,IPC_NOWAIT);
    50. if(strlen(msg.mtext)!=0)
    51. {
    52. putchar(10);
    53. printf("读取到的消息为:%s\n",msg.mtext);
    54. printf("请输入:");
    55. fflush(stdout);
    56. }
    57. else
    58. {
    59. ;
    60. }
    61. }
    62. else if(brr==1)
    63. {
    64. memset(&msg,0,sizeof(msg));
    65. msgrcv(id,&msg,128,*mytype,IPC_NOWAIT|020000);
    66. if(strlen(msg.mtext)!=0)
    67. {
    68. putchar(10);
    69. printf("读取到的消息为:%s\n",msg.mtext);
    70. printf("请输入:");
    71. fflush(stdout);
    72. }
    73. else
    74. {
    75. ;
    76. }
    77. }
    78. }
    79. }
    80. void handler(int signum)
    81. {
    82. if(signum==SIGINT)
    83. {
    84. brr=(brr+1)%2;
    85. printf("%d\n",brr);
    86. }
    87. }
    88. int main(int argc, const char *argv[])
    89. {
    90. pthread_t id1;
    91. int mytype1=atoi(argv[2]);
    92. pthread_create(&id1,0,run,&mytype1);
    93. int mytype=atoi(argv[1]);
    94. key_t key=ftok("./ipc",1);
    95. if(key==-1)
    96. {
    97. perror("ftok");
    98. return 1;
    99. }
    100. int id=msgget(key,IPC_CREAT|0666);
    101. if(id==-1)
    102. {
    103. perror("msgget");
    104. return 1;
    105. }
    106. struct msgbuf msg;
    107. int size=0;
    108. signal(SIGINT,handler);
    109. while(1)
    110. {
    111. memset(&msg,0,sizeof(msg));
    112. msg.mtype=mytype;
    113. printf("请输入:");
    114. scanf("%128s",msg.mtext);
    115. while(getchar()!='\n');
    116. size=strlen(msg.mtext);
    117. msgsnd(id,&msg,size,0);
    118. }
    119. return 0;
    120. }

  • 相关阅读:
    德国人工智能公司【Kodex AI】完成160万欧元融资
    三、Ocelot请求聚合与负载均衡
    2、JSP——配置Tomcat服务器
    【day9.30】消息队列实现进程间通信
    Chrome命令大全
    R语言统计与绘图:生存曲线的两两比较
    【无标题】
    C语言趣味代码(一)
    服务注册中心Eureka
    成功解决ImportError: cannot import name ‘_validate_lengths‘
  • 原文地址:https://blog.csdn.net/sgjxbpdhc/article/details/138821762