【问题标题】:How to received ten message queues and print them in reverse order?如何接收十个消息队列并以相反的顺序打印它们?
【发布时间】:2019-10-31 13:58:19
【问题描述】:

主要任务 - 编写两个程序:第一个将发送 10 条消息,第二个取决于调用参数 - eter 将根据用户的选择以相同或相反的顺序接收它们。

我有两个工作程序:一个轮流发送10个字,另一个接收和输出。问题是我不知道如何让第二个程序以相反的顺序显示这些单词(从最后一个开始) - 我需要为用户选择他想要的顺序!

//Program for receive messages :

#include<stdio.h>
 #include<sys/ipc.h>
 #include<sys/msg.h>
 #include<sys/types.h>

 struct msgbuf {
 long type;
 char mtext[1000];
 };

 void receive_message(int mqid,int argum)
 {
         int j=0;
 struct msgbuf buffer;

 for(int i = 0;i<10;i++){

 if(msgrcv(mqid,&buffer,sizeof(buffer.mtext),1,0)<0){
 perror("msgrcv");
 } else{

 printf("Received message [%d] : %s\n",i,buffer.mtext);

 }
 }
 }


 int main(int argc,char *argv[])
 {
 int key = ftok("ed",8);
 if(key<0)
 perror("ftok");

 int id = msgget(key,0600|IPC_CREAT|IPC_EXCL);
 if(id<0)
 perror("msgget");
 receive_message(id,argc);

 if(msgctl(id,IPC_RMID,0)<0)
 perror("msgctl");

 return 0;
 }

//Program for send messages

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

 #define TEXT_LENGTH 1000

 struct msgbuf {
 long type;
 char mtext[TEXT_LENGTH];
 };

 void send_message(int mqid)
 {
 struct msgbuf buffer;
int y;
 buffer.type = 1;

char message[100];

 for(int i = 0;i<10;i++){

puts("Enter word : ");
scanf("%s",&message);

memset(buffer.mtext,0,sizeof(buffer.mtext));
 strncpy(buffer.mtext,message,TEXT_LENGTH-1);

 if(msgsnd(mqid,&buffer,sizeof(buffer.mtext),0)<0)
 perror("msgsnd");
 }
 }

 int main(void) {
 int key = ftok("ed",8);
 if(key<0)
 perror("ftok");

 int id = msgget(key,0600);
 if(id<0)
 perror("msgget");

 send_message(id);

 return 0;
 }

没有错误;该程序仅显示我输入的 10 个单词

【问题讨论】:

  • 也许您可以使用mtype 字段并发送类型为 10(或其他最大值)、9、... 2、1 降序的消息。接收方可以使用msgtyp = 0按发送顺序获取消息或msgtyp &lt; 0按升序获取消息(mtype msgtyp=-11(或 -999 ...)
  • 或者如果您希望接收方等到发送方发送完所有消息,请使用msgtyp=-2,然后使用msgtyp=-3、4、5 等。

标签: c linux ubuntu


【解决方案1】:

如果你想反转,继续添加到链表的尾部,然后从头到尾显示

【讨论】:

    猜你喜欢
    • 2011-06-14
    • 2010-09-19
    • 2014-07-08
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    相关资源
    最近更新 更多