【问题标题】:Message receive program only printing every other message消息接收程序仅打印每隔一条消息
【发布时间】:2016-07-03 15:38:09
【问题描述】:

我已经实现了http://beej.us/guide/bgipc/output/html/multipage/mq.html 第 7.6 节中的两个程序。

我已经扩展了它,以便有两个接收程序,它去哪一个是由消息类型决定的。

问题出现在接收程序B和C。他们应该每次都打印出输入程序A的消息,但是他们只是每隔一段时间才打印消息。

这是发送消息的地方,它读取前 6 个字符,如果是 URGENT 则设置消息类型。

buf.mtype = 2;

while(fgets(buf.mtext, sizeof buf.mtext, stdin) != NULL) {
        int len = strlen(buf.mtext);

        strncpy(typeTest, buf.mtext, 6);

        if(strncmp(typeTest, "URGENT", 6) == 0){
            buf.mtype = 1;
        }       

        printf("This is the message %s \n", buf.mtext);

        /* ditch newline at end, if it exists */
        if (buf.mtext[len-1] == '\n') buf.mtext[len-1] = '\0';

        if (msgsnd(msqid, &buf, len+1, 0) == -1) /* +1 for '\0' */
            perror("msgsnd");
    }

这是接收消息的地方,然后 if 语句检查类型然后打印出来。

for(;;) { /* Spock never quits! */
        if (msgrcv(msqid, &buf, sizeof buf.mtext, 0, 0) == -1) {
            perror("msgrcv");
            exit(1);
        }

        if(buf.mtype == 2){
            printf("spock: \"%s\"\n", buf.mtext);
        }
    }

谁能解释为什么它只打印出所有其他消息?

谢谢。

【问题讨论】:

  • mtype 总是2 吗?决定将消息发送到哪里的调度员在哪里,你的 B 和 C?是否可能将一条消息路由到 B,而将另一条消息路由到 C?
  • 请注意,如果类型不是“紧急”,则不要将 buf.mtype 设置为 2。一旦设置为 1,它将始终保持为 1。
  • 抱歉,我没有将它包含在代码 sn-p 中,mtype 在 A 中的 while 循环之前设置为两个,buf.mtype = 2;。如果前六个字符是“紧急”,则将 mtype 设置为 1。如果 mtype 为 1,C 读取它,如果 2 B 读取它。
  • 再次声明:如果类型不是“紧急”,则不要将 buf.mtype 设置为 2。一旦设置为 1,它将始终保持为 1。您必须在循环中执行此操作,而不是在循环之外。
  • 您必须调用msgrcvmsgtype 为 1 或 2。零只会从队列中获取下一条消息。

标签: c linux ipc message-queue msgrcv


【解决方案1】:

在您的程序 A 中,如果输入不是“URGENT...”,则必须将 buf.mtype 设置为 2,您必须每次都在循环中这样做。

while(fgets(buf.mtext, sizeof buf.mtext, stdin) != NULL) {
    int len = strlen(buf.mtext);

    strncpy(typeTest, buf.mtext, 6);

    if(strncmp(typeTest, "URGENT", 6) == 0){
        buf.mtype = 1;
    }       
    else buf.mtype= 2;    // always set the default

    printf("This is the message %s \n", buf.mtext);

    /* ditch newline at end, if it exists */
    if (buf.mtext[len-1] == '\n') buf.mtext[len-1] = '\0';

    if (msgsnd(msqid, &buf, len+1, 0) == -1) /* +1 for '\0' */
        perror("msgsnd");
}

在您的程序 B 和 C 中,您必须将每个程序的 msgtyp 设置为 1 或 2,以便从队列中获取正确的消息,例如:

int main(argc, argv)
{
    int msgtype;
    if (*argv[1]=='A')
        msgtype= 1;
    else if (*argv[1]=='B')
        msgtype= 2;
    else
        msgtype= 0;
    ...
    for(;;) { /* Spock never quits! */
        if (msgrcv(msqid, &buf, sizeof buf.mtext, msgtype, 0) == -1) {
            perror("msgrcv");
            exit(1);
        }

        if(buf.mtype == msgtype){
            printf("spock: \"%s\"\n", buf.mtext);
        }
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    相关资源
    最近更新 更多