消息接收程序只打印每隔一条消息

Message receive program only printing every other message

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

我把它扩展成两个接收程序,去哪一个由消息类型决定。

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

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

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] = '[=10=]';

        if (msgsnd(msqid, &buf, len+1, 0) == -1) /* +1 for '[=10=]' */
            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);
        }
    }

谁能解释一下为什么它只打印出每隔一条消息?

谢谢。

在你的程序 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] = '[=10=]';

    if (msgsnd(msqid, &buf, len+1, 0) == -1) /* +1 for '[=10=]' */
        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;
}